1

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 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

3 Comments

Thank you for your solution! However, I don't know how to call the service from drupal custom page.
You can call this from your custom route's controller method with \Drupal::service('your.custom.service')->giveNumber();
Worth to quote drupal.org saying: Dependency injection is the preferred method for accessing and using services in Drupal 8 and should be used whenever possible. Rather than calling out to the global services container, services are instead passed as arguments to a constructor or injected via setter methods.
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.