Score:0

How to use a Controller method inside a service with dependency injection?

cn flag

I'm using the diff module for a project, this module has a method inside a Controller that I want to use in a service to reuse code. As this time I'm just calling the method like PluginRevisionController::getRevisionIds() but this give me the message:

Deprecated function: Non-static method Drupal\diff\Controller\PluginRevisionController::getRevisionIds() should not be called statically

So, I want to 'inject' if possible in some way the Controller (I really don't know if this is possible) inside the service to reuse the logic. There is a way to do this?

No Sssweat avatar
ua flag
Bad diff module design, that method should've been in a service.
Score:6
us flag

You could inject a ClassResolverInterface or ControllerResolverInterface into your service to load a controller instance.

From core.services.yml:

controller_resolver:
  class: Drupal\Core\Controller\ControllerResolver
  arguments: ['@psr7.http_message_factory', '@class_resolver']
class_resolver:
  class: Drupal\Core\DependencyInjection\ClassResolver
  calls:
    - [setContainer, ['@service_container']]

Both classes will return an instance, just the method names differ.

$controller = $this->classResolver->getInstanceFromDefinition(PluginRevisionController::class);
$controller = $this->controllerResolver->getControllerFromDefinition(PluginRevisionController::class);
I sit in a Tesla and translated this thread with Ai:

mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.