1

I want to use a function in both a controller and a module. where should I define that function?

Can I call a function in module from a controller? How I can do that?

2 Answers 2

2

This is exactly the case when you define a Service:

  • In your controller you call the service with Dependency injection
  • In your module you call the static \Drupal::service('..')
1
  • This is recommend yes, but you can always also call any function in a .module file, they are always loaded.
    – Berdir
    Jun 18, 2016 at 18:12
1

First off, a controller is just an instance of a class. As such, calling a function from a controller is not different from what you would do in another PHP class. To answer your questions:

  • Where should I define that function? You can define it in the module file, since that is already loaded when a controller object is created and its methods are called.

  • Can I call a function in module from a controller? How I can do that? Yes, you can, and you don't need to do something more than calling the function as you would call it from another function, since modules are already loaded when a controller object is created.

Comparing a single function with a service doesn't make much sense; you will never replace a function like taxonomy_get_title() with a service. I would rather compare a service with a group of related function, and in that case, I would say that a service is preferable to a group of related functions.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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