2

What is the best way to find right service for dependency injection? Googling is not efficient yet. For example I spent quite long time figuring out that if I need current request passed to constructor by DI I have too use:

$container->get('request_stack')->getCurrentRequest()

Full code example:

/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
    return new static(
        $configuration,
        $plugin_id,
        $plugin_definition,
        $container->getParameter('serializer.formats'),
        $container->get('logger.factory')->get('job_market'),
        $container->get('current_user'),
        $container->get('request_stack')->getCurrentRequest()
    );
}

And I've found above example in drupal class Documentation

Before that I've just found this services list but there is no description, no examples, nothing. Just a list with possibility to search.

How do you search for right service provider?

2

A better way to accomplish this is to use the Drupal Console's container:debug command. This command outputs a list of Drupal service ID's and its corresponding namespace & class.

$drupal container:debug  

 Service ID                 Class Name
 class_loader               Symfony\Component\ClassLoader\ApcClassLoader
 kernel                     Drupal\Core\DrupalKernel
 service_container          Drupal\Core\DependencyInjection\Container
 cache_context.ip           Drupal\Core\Cache\Context\IpCacheContext
 cache_context.headers      Drupal\Core\Cache\Context\HeadersCacheContext
 cache_context.cookies      Drupal\Core\Cache\Context\CookiesCacheContext
 ...

This command can be employed along with grep to search for a specific class name or service ID. For example: drupal container:debug | ag 'DatabaseStorage' to find a DatabaseStorage class.

Also of interest is the PhpStorm / IntelliJ Drupal Symfony Bridge plugin if you use PHPStorm.

1
  • That's a good one but still it's missing description. So for example when you need current Request you have to use request_stack which is not so obvious. Description will definitely do the trick. For example: request_stack - allow you to get current request and do bunch of other stuff :) Oct 14 '16 at 7:12

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.