In a controller you inject services by using the service container. For example ModuleHandler:
namespace Drupal\mymodule\Controller; use Drupal\Core\Controller\ControllerBase; use Symfony\Component\DependencyInjection\ContainerInterface; use Drupal\Core\Extension\ModuleHandlerInterface; class MyController extends ControllerBase { /** * The module handler service. * * @var \Drupal\Core\Extension\ModuleHandlerInterface */ protected $moduleHandler; /** * Constructs a MyController object * * @param \Drupal\Core\Extension\ModuleHandlerInterface $module_handler * The module handler service. */ public function __construct(ModuleHandlerInterface $module_handler) { $this->moduleHandler = $module_handler; } /** * {@inheritdoc} */ public static function create(ContainerInterface $container) { return new static( $container->get('module_handler') ); }
Then you can avoid \Drupal calls by using the injected service:
$this->moduleHandler->alter('mymodule_myfunction', $plugin_items);
You can inject any service, existing ones from core/contrib or services you've defined in custom code in a *.services.yml file.
To find a core service name I usually look into core.services.yml, because that's the quickest way when you are working on a drupal project in your IDE.
You can use Drupal Console to list all services, not only from core:
drupal debug:container
You can also use the Devel module, which allows you to search for a name:
/devel/container/service
createwill overload the parent method - here you can inject the services you need. The constructor will then let you assign those to instance variables in the class, so you can use$this->fooInjectedClass->methodName()