Service Subscribers & Locators

Service Subscribers & Locators

Sometimes, a service needs access to several other services without being sure that all of them will actually be used. In those cases, you may want the instantiation of the services to be lazy. However, that’s not possible using the explicit dependency injection since services are not all meant to be lazy (see Lazy Services).

This can typically be the case in your controllers, where you may inject several services in the constructor, but the action called only uses some of them. Another example are applications that implement the Command pattern using a CommandBus to map command handlers by Command class names and use them to handle their respective command when it is asked for:

  1. // src/CommandBus.php
  2. namespace App;
  3. // ...
  4. class CommandBus
  5. {
  6. /**
  7. * @var CommandHandler[]
  8. */
  9. private $handlerMap;
  10. public function __construct(array $handlerMap)
  11. {
  12. $this->handlerMap = $handlerMap;
  13. }
  14. public function handle(Command $command)
  15. {
  16. $commandClass = get_class($command);
  17. if (!isset($this->handlerMap[$commandClass])) {
  18. return;
  19. }
  20. return $this->handlerMap[$commandClass]->handle($command);
  21. }
  22. }
  23. // ...
  24. $commandBus->handle(new FooCommand());

Considering that only one command is handled at a time, instantiating all the other command handlers is unnecessary. A possible solution to lazy-load the handlers could be to inject the main dependency injection container.

However, injecting the entire container is discouraged because it gives too broad access to existing services and it hides the actual dependencies of the services. Doing so also requires services to be made public, which isn’t the case by default in Symfony applications.

Service Subscribers are intended to solve this problem by giving access to a set of predefined services while instantiating them only when actually needed through a Service Locator, a separate lazy-loaded container.

Defining a Service Subscriber

First, turn CommandBus into an implementation of Symfony\Component\DependencyInjection\ServiceSubscriberInterface. Use its getSubscribedServices() method to include as many services as needed in the service subscriber and change the type hint of the container to a PSR-11 ContainerInterface:

  1. // src/CommandBus.php
  2. namespace App;
  3. use App\CommandHandler\BarHandler;
  4. use App\CommandHandler\FooHandler;
  5. use Psr\Container\ContainerInterface;
  6. use Symfony\Contracts\Service\ServiceSubscriberInterface;
  7. class CommandBus implements ServiceSubscriberInterface
  8. {
  9. private $locator;
  10. public function __construct(ContainerInterface $locator)
  11. {
  12. $this->locator = $locator;
  13. }
  14. public static function getSubscribedServices(): array
  15. {
  16. return [
  17. 'App\FooCommand' => FooHandler::class,
  18. 'App\BarCommand' => BarHandler::class,
  19. ];
  20. }
  21. public function handle(Command $command)
  22. {
  23. $commandClass = get_class($command);
  24. if ($this->locator->has($commandClass)) {
  25. $handler = $this->locator->get($commandClass);
  26. return $handler->handle($command);
  27. }
  28. }
  29. }

Tip

If the container does not contain the subscribed services, double-check that you have autoconfigure enabled. You can also manually add the container.service_subscriber tag.

The injected service is an instance of Symfony\Component\DependencyInjection\ServiceLocator which implements the PSR-11 ContainerInterface, but it is also a callable:

  1. // ...
  2. $handler = ($this->locator)($commandClass);
  3. return $handler->handle($command);

Including Services

In order to add a new dependency to the service subscriber, use the getSubscribedServices() method to add service types to include in the service locator:

  1. use Psr\Log\LoggerInterface;
  2. public static function getSubscribedServices(): array
  3. {
  4. return [
  5. // ...
  6. LoggerInterface::class,
  7. ];
  8. }

Service types can also be keyed by a service name for internal use:

  1. use Psr\Log\LoggerInterface;
  2. public static function getSubscribedServices(): array
  3. {
  4. return [
  5. // ...
  6. 'logger' => LoggerInterface::class,
  7. ];
  8. }

When extending a class that also implements ServiceSubscriberInterface, it’s your responsibility to call the parent when overriding the method. This typically happens when extending AbstractController:

  1. use Psr\Log\LoggerInterface;
  2. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  3. class MyController extends AbstractController
  4. {
  5. public static function getSubscribedServices(): array
  6. {
  7. return array_merge(parent::getSubscribedServices(), [
  8. // ...
  9. 'logger' => LoggerInterface::class,
  10. ]);
  11. }
  12. }

Optional Services

For optional dependencies, prepend the service type with a ? to prevent errors if there’s no matching service found in the service container:

  1. use Psr\Log\LoggerInterface;
  2. public static function getSubscribedServices(): array
  3. {
  4. return [
  5. // ...
  6. '?'.LoggerInterface::class,
  7. ];
  8. }

Note

Make sure an optional service exists by calling has() on the service locator before calling the service itself.

Aliased Services

By default, autowiring is used to match a service type to a service from the service container. If you don’t use autowiring or need to add a non-traditional service as a dependency, use the container.service_subscriber tag to map a service type to a service.

  • YAML

    1. # config/services.yaml
    2. services:
    3. App\CommandBus:
    4. tags:
    5. - { name: 'container.service_subscriber', key: 'logger', id: 'monolog.logger.event' }
  • XML

    1. <!-- config/services.xml -->
    2. <?xml version="1.0" encoding="UTF-8" ?>
    3. <container xmlns="http://symfony.com/schema/dic/services"
    4. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    5. xsi:schemaLocation="http://symfony.com/schema/dic/services https://symfony.com/schema/dic/services/services-1.0.xsd">
    6. <services>
    7. <service id="App\CommandBus">
    8. <tag name="container.service_subscriber" key="logger" id="monolog.logger.event"/>
    9. </service>
    10. </services>
    11. </container>
  • PHP

    1. // config/services.php
    2. namespace Symfony\Component\DependencyInjection\Loader\Configurator;
    3. use App\CommandBus;
    4. return function(ContainerConfigurator $configurator) {
    5. $services = $configurator->services();
    6. $services->set(CommandBus::class)
    7. ->tag('container.service_subscriber', ['key' => 'logger', 'id' => 'monolog.logger.event']);
    8. };

Tip

The key attribute can be omitted if the service name internally is the same as in the service container.

Defining a Service Locator

To manually define a service locator and inject it to another service, create an argument of type service_locator:

  • YAML

    1. # config/services.yaml
    2. services:
    3. App\CommandBus:
    4. arguments: !service_locator
    5. App\FooCommand: '@app.command_handler.foo'
    6. App\BarCommand: '@app.command_handler.bar'
  • XML

    1. <!-- config/services.xml -->
    2. <?xml version="1.0" encoding="UTF-8" ?>
    3. <container xmlns="http://symfony.com/schema/dic/services"
    4. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    5. xsi:schemaLocation="http://symfony.com/schema/dic/services https://symfony.com/schema/dic/services/services-1.0.xsd">
    6. <services>
    7. <service id="App\CommandBus">
    8. <argument type="service_locator">
    9. <argument key="App\FooCommand" type="service" id="sapp.command_handler.foo"/>
    10. <argument key="App\BarCommandr" type="service" id="app.command_handler.bar"/>
    11. <!-- if the element has no key, the ID of the original service is used -->
    12. <argument type="service" id="app.command_handler.baz"/>
    13. </argument>
    14. </service>
    15. </services>
    16. </container>
  • PHP

    1. // config/services.php
    2. namespace Symfony\Component\DependencyInjection\Loader\Configurator;
    3. use App\CommandBus;
    4. return function(ContainerConfigurator $configurator) {
    5. $services = $configurator->services();
    6. $services->set(CommandBus::class)
    7. ->args([service_locator([
    8. 'App\FooCommand' => ref('app.command_handler.foo'),
    9. 'App\BarCommand' => ref('app.command_handler.bar'),
    10. // if the element has no key, the ID of the original service is used
    11. ref('app.command_handler.baz'),
    12. ])]);
    13. };

New in version 4.2: The ability to add services without specifying an array key was introduced in Symfony 4.2.

New in version 4.2: The service_locator argument type was introduced in Symfony 4.2.

As shown in the previous sections, the constructor of the CommandBus class must type-hint its argument with ContainerInterface. Then, you can get any of the service locator services via their ID (e.g. $this->locator->get('App\FooCommand')).

Reusing a Service Locator in Multiple Services

If you inject the same service locator in several services, it’s better to define the service locator as a stand-alone service and then inject it in the other services. To do so, create a new service definition using the ServiceLocator class:

  • YAML

    1. # config/services.yaml
    2. services:
    3. app.command_handler_locator:
    4. class: Symfony\Component\DependencyInjection\ServiceLocator
    5. arguments:
    6. -
    7. App\FooCommand: '@app.command_handler.foo'
    8. App\BarCommand: '@app.command_handler.bar'
    9. # if you are not using the default service autoconfiguration,
    10. # add the following tag to the service definition:
    11. # tags: ['container.service_locator']
    12. # if the element has no key, the ID of the original service is used
    13. app.another_command_handler_locator:
    14. class: Symfony\Component\DependencyInjection\ServiceLocator
    15. arguments:
    16. -
    17. - '@app.command_handler.baz'
  • XML

    1. <!-- config/services.xml -->
    2. <?xml version="1.0" encoding="UTF-8" ?>
    3. <container xmlns="http://symfony.com/schema/dic/services"
    4. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    5. xsi:schemaLocation="http://symfony.com/schema/dic/services https://symfony.com/schema/dic/services/services-1.0.xsd">
    6. <services>
    7. <service id="app.command_handler_locator" class="Symfony\Component\DependencyInjection\ServiceLocator">
    8. <argument type="collection">
    9. <argument key="App\FooCommand" type="service" id="app.command_handler.foo"/>
    10. <argument key="App\BarCommand" type="service" id="app.command_handler.bar"/>
    11. <!-- if the element has no key, the ID of the original service is used -->
    12. <argument type="service" id="app.command_handler.baz"/>
    13. </argument>
    14. <!--
    15. if you are not using the default service autoconfiguration,
    16. add the following tag to the service definition:
    17. <tag name="container.service_locator"/>
    18. -->
    19. </service>
    20. </services>
    21. </container>
  • PHP

    1. // config/services.php
    2. namespace Symfony\Component\DependencyInjection\Loader\Configurator;
    3. use Symfony\Component\DependencyInjection\ServiceLocator;
    4. return function(ContainerConfigurator $configurator) {
    5. $services = $configurator->services();
    6. $services->set('app.command_handler_locator', ServiceLocator::class)
    7. ->args([[
    8. 'App\FooCommand' => ref('app.command_handler.foo'),
    9. 'App\BarCommand' => ref('app.command_handler.bar'),
    10. ]])
    11. // if you are not using the default service autoconfiguration,
    12. // add the following tag to the service definition:
    13. // ->tag('container.service_locator')
    14. ;
    15. // if the element has no key, the ID of the original service is used
    16. $services->set('app.another_command_handler_locator', ServiceLocator::class)
    17. ->args([[
    18. ref('app.command_handler.baz'),
    19. ]])
    20. ;
    21. };

New in version 4.1: The service locator autoconfiguration was introduced in Symfony 4.1. In previous Symfony versions you always needed to add the container.service_locator tag explicitly.

Now you can inject the service locator in any other services:

  • YAML

    1. # config/services.yaml
    2. services:
    3. App\CommandBus:
    4. arguments: ['@app.command_handler_locator']
  • XML

    1. <!-- config/services.xml -->
    2. <?xml version="1.0" encoding="UTF-8" ?>
    3. <container xmlns="http://symfony.com/schema/dic/services"
    4. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    5. xsi:schemaLocation="http://symfony.com/schema/dic/services https://symfony.com/schema/dic/services/services-1.0.xsd">
    6. <services>
    7. <service id="App\CommandBus">
    8. <argument type="service" id="app.command_handler_locator"/>
    9. </service>
    10. </services>
    11. </container>
  • PHP

    1. // config/services.php
    2. namespace Symfony\Component\DependencyInjection\Loader\Configurator;
    3. use App\CommandBus;
    4. return function(ContainerConfigurator $configurator) {
    5. $services = $configurator->services();
    6. $services->set(CommandBus::class)
    7. ->args([ref('app.command_handler_locator')]);
    8. };

Using Service Locators in Compiler Passes

In compiler passes it’s recommended to use the [register()](https://github.com/symfony/symfony/blob/4.4/src/Symfony/Component/DependencyInjection/Compiler/ServiceLocatorTagPass.php "Symfony\Component\DependencyInjection\Compiler\ServiceLocatorTagPass::register()") method to create the service locators. This will save you some boilerplate and will share identical locators among all the services referencing them:

  1. use Symfony\Component\DependencyInjection\Compiler\ServiceLocatorTagPass;
  2. use Symfony\Component\DependencyInjection\ContainerBuilder;
  3. use Symfony\Component\DependencyInjection\Reference;
  4. public function process(ContainerBuilder $container): void
  5. {
  6. // ...
  7. $locateableServices = [
  8. // ...
  9. 'logger' => new Reference('logger'),
  10. ];
  11. $myService->addArgument(ServiceLocatorTagPass::register($container, $locateableServices));
  12. }

Indexing the Collection of Services

Services passed to the service locator can define their own index using an arbitrary attribute whose name is defined as index_by in the service locator.

In the following example, the App\Handler\HandlerCollection locator receives all services tagged with app.handler and they are indexed using the value of the key tag attribute (as defined in the index_by locator option):

  • YAML

    1. # config/services.yaml
    2. services:
    3. App\Handler\One:
    4. tags:
    5. - { name: 'app.handler', key: 'handler_one' }
    6. App\Handler\Two:
    7. tags:
    8. - { name: 'app.handler', key: 'handler_two' }
    9. App\Handler\HandlerCollection:
    10. # inject all services tagged with app.handler as first argument
    11. arguments: [!tagged_locator { tag: 'app.handler', index_by: 'key' }]
  • XML

    1. <!-- config/services.xml -->
    2. <?xml version="1.0" encoding="UTF-8" ?>
    3. <container xmlns="http://symfony.com/schema/dic/services"
    4. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    5. xsi:schemaLocation="http://symfony.com/schema/dic/services
    6. https://symfony.com/schema/dic/services/services-1.0.xsd">
    7. <services>
    8. <service id="App\Handler\One">
    9. <tag name="app.handler" key="handler_one"/>
    10. </service>
    11. <service id="App\Handler\Two">
    12. <tag name="app.handler" key="handler_two"/>
    13. </service>
    14. <service id="App\HandlerCollection">
    15. <!-- inject all services tagged with app.handler as first argument -->
    16. <argument type="tagged_locator" tag="app.handler" index-by="key"/>
    17. </service>
    18. </services>
    19. </container>
  • PHP

    1. // config/services.php
    2. namespace Symfony\Component\DependencyInjection\Loader\Configurator;
    3. return function(ContainerConfigurator $configurator) {
    4. $services = $configurator->services();
    5. $services->set(App\Handler\One::class)
    6. ->tag('app.handler', ['key' => 'handler_one'])
    7. ;
    8. $services->set(App\Handler\Two::class)
    9. ->tag('app.handler', ['key' => 'handler_two'])
    10. ;
    11. $services->set(App\Handler\HandlerCollection::class)
    12. // inject all services tagged with app.handler as first argument
    13. ->args([tagged_locator('app.handler', 'key')])
    14. ;
    15. };

Inside this locator you can retrieve services by index using the value of the key attribute. For example, to get the App\Handler\Two service:

  1. // src/Handler/HandlerCollection.php
  2. namespace App\Handler;
  3. use Symfony\Component\DependencyInjection\ServiceLocator;
  4. class HandlerCollection
  5. {
  6. public function __construct(ServiceLocator $locator)
  7. {
  8. $handlerTwo = $locator->get('handler_two');
  9. }
  10. // ...
  11. }

Instead of defining the index in the service definition, you can return its value in a method called getDefaultIndexName() inside the class associated to the service:

  1. // src/Handler/One.php
  2. namespace App\Handler;
  3. class One
  4. {
  5. public static function getDefaultIndexName(): string
  6. {
  7. return 'handler_one';
  8. }
  9. // ...
  10. }

If you prefer to use another method name, add a default_index_method attribute to the locator service defining the name of this custom method:

  • YAML

    1. # config/services.yaml
    2. services:
    3. # ...
    4. App\HandlerCollection:
    5. arguments: [!tagged_locator { tag: 'app.handler', index_by: 'key', default_index_method: 'myOwnMethodName' }]
  • XML

    1. <!-- config/services.xml -->
    2. <?xml version="1.0" encoding="UTF-8" ?>
    3. <container xmlns="http://symfony.com/schema/dic/services"
    4. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    5. xsi:schemaLocation="http://symfony.com/schema/dic/services
    6. https://symfony.com/schema/dic/services/services-1.0.xsd">
    7. <services>
    8. <!-- ... -->
    9. <service id="App\HandlerCollection">
    10. <argument type="tagged_locator" tag="app.handler" index-by="key" default-index-method="myOwnMethodName"/>
    11. </service>
    12. </services>
    13. </container>
  • PHP

    1. // config/services.php
    2. namespace Symfony\Component\DependencyInjection\Loader\Configurator;
    3. return function(ContainerConfigurator $configurator) {
    4. $configurator->services()
    5. ->set(App\HandlerCollection::class)
    6. ->args([tagged_locator('app.handler', 'key', 'myOwnMethodName')])
    7. ;
    8. };

Note

Since code should not be responsible for defining how the locators are going to be used, a configuration key (key in the example above) must be set so the custom method may be called as a fallback.

Service Subscriber Trait

The Symfony\Contracts\Service\ServiceSubscriberTrait provides an implementation for Symfony\Contracts\Service\ServiceSubscriberInterface that looks through all methods in your class that have no arguments and a return type. It provides a ServiceLocator for the services of those return types. The service id is __METHOD__. This allows you to add dependencies to your services based on type-hinted helper methods:

  1. // src/Service/MyService.php
  2. namespace App\Service;
  3. use Psr\Log\LoggerInterface;
  4. use Symfony\Component\Routing\RouterInterface;
  5. use Symfony\Contracts\Service\ServiceSubscriberInterface;
  6. use Symfony\Contracts\Service\ServiceSubscriberTrait;
  7. class MyService implements ServiceSubscriberInterface
  8. {
  9. use ServiceSubscriberTrait;
  10. public function doSomething()
  11. {
  12. // $this->router() ...
  13. // $this->logger() ...
  14. }
  15. private function router(): RouterInterface
  16. {
  17. return $this->container->get(__METHOD__);
  18. }
  19. private function logger(): LoggerInterface
  20. {
  21. return $this->container->get(__METHOD__);
  22. }
  23. }

This allows you to create helper traits like RouterAware, LoggerAware, etc… and compose your services with them:

  1. // src/Service/LoggerAware.php
  2. namespace App\Service;
  3. use Psr\Log\LoggerInterface;
  4. trait LoggerAware
  5. {
  6. private function logger(): LoggerInterface
  7. {
  8. return $this->container->get(__CLASS__.'::'.__FUNCTION__);
  9. }
  10. }
  11. // src/Service/RouterAware.php
  12. namespace App\Service;
  13. use Symfony\Component\Routing\RouterInterface;
  14. trait RouterAware
  15. {
  16. private function router(): RouterInterface
  17. {
  18. return $this->container->get(__CLASS__.'::'.__FUNCTION__);
  19. }
  20. }
  21. // src/Service/MyService.php
  22. namespace App\Service;
  23. use Symfony\Contracts\Service\ServiceSubscriberInterface;
  24. use Symfony\Contracts\Service\ServiceSubscriberTrait;
  25. class MyService implements ServiceSubscriberInterface
  26. {
  27. use ServiceSubscriberTrait, LoggerAware, RouterAware;
  28. public function doSomething()
  29. {
  30. // $this->router() ...
  31. // $this->logger() ...
  32. }
  33. }

Caution

When creating these helper traits, the service id cannot be __METHOD__ as this will include the trait name, not the class name. Instead, use __CLASS__.'::'.__FUNCTION__ as the service id.

This work, including the code samples, is licensed under a Creative Commons BY-SA 3.0 license.