1
votes

I am new to Drupal web development. I have already used Wordpress platform by building a custom plugin to write custom php functions, and calling the function from a custom page was easy.

example:

<?php
function givenumber(){
  return 50;
}
?>;

Which I call by using:

<?php  echo givenumber(); ?>
  • How can I achieve similar with Drupal 8?
  • Do I need to create a custom module for writing the custom php functions?
  • How do I call a function from a custom page?

Please help.

2

2 Answers

1
votes

The best way to do this in Drupal 8 is to create a service in a custom module yes.

Create a module with the following structure:

your_custom_module/
├── your_custom_module.info.yml
├── your_custom_module.services.yml
└── src/
    └── YourCustomService.php

Your your_custom_module.services.yml file:

services:
  your.custom.service:
    class: Drupal\your_custom_module\YourCustomService

Your Service class:

<?php

namespace Drupal\your_custom_module;

class YourCustomService {

  public function giveNumber() {
    return 1234;
  }

}

Enable the module and you can now call this service:

\Drupal::service('your.custom.service')->giveNumber();

See more details in Structure of a service file

0
votes

There is 'N' number of ways. And, it depends on your use case.

If you want some custom value and just show in your content page. There are hook_preprocess_node() functions that you can write in your active theme, and make some variables available to your twig file.