0

I want to create a class with list of helper functions, so I created a module and placed the helper functions inside it. I created a service.yml inside that module folder.

services:
  helpers.helpers:
    class: Helpers

Helper class file:

class Helpers {
   public function buildPage($page_template, $template_variables) {
      echo "Dheivamey oru vazhiya"
   }
}

I make it as a dependency inside another module.

dependencies:
  - helpers:helpers

I tried using it inside a controller file like this

public function buildSomePage(Request $request) {
  $helper = \Drupal::service('helpers.helpers');
}

But I am getting a Helpers class not found error. Someone help me before my head explode.

3
  • 1
    The path to your class in the service definition is incorrect. It needs to be the full path to the class under the \Drupal namespace. Is this all of the code? If so you’re missing more. Check the documentation for creating service objects. Besides that, your controller should be injecting dependencies, instead of use \Drupal::service.
    – Kevin
    Dec 27, 2018 at 15:24
  • I used the namespace namespace Drupal\module_name\Service, but still it showed the same error, so thats why I tried removing namespace
    – Abel
    Dec 27, 2018 at 15:48
  • 2

1 Answer 1

0

This issue resolved after I included the full namespace from Drupal\module-name and placed the file inside the src folder. I included the namespace earlier, but I missed placing the corresponding "Helper" file in the src directory.

1
  • Meanwhile if we want to use service using dependancy injection, (of course a suggested best practice) we have to override the static create function as mentioned here.
    – Abel
    Dec 28, 2018 at 10:11

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.