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).
See also
Another way to inject services lazily is via a service closure.
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 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
// src/CommandBus.php
namespace App;
// ...
class CommandBus
{
/**
* @var CommandHandler[]
*/
private $handlerMap;
public function __construct(array $handlerMap)
{
$this->handlerMap = $handlerMap;
}
public function handle(Command $command)
{
$commandClass = get_class($command);
if (!isset($this->handlerMap[$commandClass])) {
return;
}
return $this->handlerMap[$commandClass]->handle($command);
}
}
// ...
$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 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 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
// src/CommandBus.php
namespace App;
use App\CommandHandler\BarHandler;
use App\CommandHandler\FooHandler;
use Psr\Container\ContainerInterface;
use Symfony\Contracts\Service\ServiceSubscriberInterface;
class CommandBus implements ServiceSubscriberInterface
{
private $locator;
public function __construct(ContainerInterface $locator)
{
$this->locator = $locator;
}
public static function getSubscribedServices(): array
{
return [
'App\FooCommand' => FooHandler::class,
'App\BarCommand' => BarHandler::class,
];
}
public function handle(Command $command)
{
$commandClass = get_class($command);
if ($this->locator->has($commandClass)) {
$handler = $this->locator->get($commandClass);
return $handler->handle($command);
}
}
}
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 ServiceLocator
which implements the PSR-11 ContainerInterface
, but it is also a callable:
1 2 3 4
// ...
$handler = ($this->locator)($commandClass);
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 2 3 4 5 6 7 8 9
use Psr\Log\LoggerInterface;
public static function getSubscribedServices(): array
{
return [
// ...
LoggerInterface::class,
];
}
Service types can also be keyed by a service name for internal use:
1 2 3 4 5 6 7 8 9
use Psr\Log\LoggerInterface;
public static function getSubscribedServices(): array
{
return [
// ...
'logger' => LoggerInterface::class,
];
}
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 2 3 4 5 6 7 8 9 10 11 12 13
use Psr\Log\LoggerInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
class MyController extends AbstractController
{
public static function getSubscribedServices(): array
{
return array_merge(parent::getSubscribedServices(), [
// ...
'logger' => LoggerInterface::class,
]);
}
}
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 2 3 4 5 6 7 8 9
use Psr\Log\LoggerInterface;
public static function getSubscribedServices(): array
{
return [
// ...
'?'.LoggerInterface::class,
];
}
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.
1 2 3 4 5
# config/services.yaml
services:
App\CommandBus:
tags:
- { name: 'container.service_subscriber', key: 'logger', id: 'monolog.logger.event' }
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
.
Consider the following CommandBus
class where you want to inject
some services into it via a service locator:
1 2 3 4 5 6 7 8 9 10 11
// src/HandlerCollection.php
namespace App;
use Symfony\Component\DependencyInjection\ServiceLocator;
class CommandBus
{
public function __construct(ServiceLocator $locator)
{
}
}
Symfony allows you to inject the service locator using YAML/XML/PHP configuration or directly via PHP attributes:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
// src/CommandBus.php
namespace App;
use Symfony\Component\DependencyInjection\Attribute\TaggedLocator;
use Symfony\Component\DependencyInjection\ServiceLocator;
class CommandBus
{
public function __construct(
// creates a service locator with all the services tagged with 'app.handler'
#[TaggedLocator('app.handler')] ServiceLocator $locator
) {
}
}
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')
).
5.3
The #[TaggedLocator]
attribute was introduced in Symfony 5.3 and requires PHP 8.
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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
# config/services.yaml
services:
app.command_handler_locator:
class: Symfony\Component\DependencyInjection\ServiceLocator
arguments:
-
App\FooCommand: '@app.command_handler.foo'
App\BarCommand: '@app.command_handler.bar'
# if you are not using the default service autoconfiguration,
# add the following tag to the service definition:
# tags: ['container.service_locator']
# if the element has no key, the ID of the original service is used
app.another_command_handler_locator:
class: Symfony\Component\DependencyInjection\ServiceLocator
arguments:
-
- '@app.command_handler.baz'
Note
The services defined in the service locator argument must include keys, which later become their unique identifiers inside the locator.
Now you can inject the service locator in any other services:
1 2 3 4
# config/services.yaml
services:
App\CommandBus:
arguments: ['@app.command_handler_locator']
Using Service Locators in Compiler Passes
In compiler passes it's recommended to use the 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 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
use Symfony\Component\DependencyInjection\Compiler\ServiceLocatorTagPass;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Reference;
public function process(ContainerBuilder $container): void
{
// ...
$locateableServices = [
// ...
'logger' => new Reference('logger'),
];
$myService = $container->findDefinition(MyService::class);
$myService->addArgument(ServiceLocatorTagPass::register($container, $locateableServices));
}
Indexing the Collection of Services
By default, services passed to the service locator are indexed using their service
IDs. You can change this behavior with two options of the tagged locator (index_by
and default_index_method
) which can be used independently or combined.
The index_by
/ indexAttribute
Option
This option defines the name of the option/attribute that stores the value used to index the services:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
// src/CommandBus.php
namespace App;
use Symfony\Component\DependencyInjection\Attribute\TaggedLocator;
use Symfony\Component\DependencyInjection\ServiceLocator;
class CommandBus
{
public function __construct(
#[TaggedLocator('app.handler', indexAttribute: 'key')]
ServiceLocator $locator
) {
}
}
In this example, the index_by
option is key
. All services define that
option/attribute, so that will be the value used to index the services. For example,
to get the App\Handler\Two
service:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
// src/Handler/HandlerCollection.php
namespace App\Handler;
use Symfony\Component\DependencyInjection\ServiceLocator;
class HandlerCollection
{
public function __construct(ServiceLocator $locator)
{
// this value is defined in the `key` option of the service
$handlerTwo = $locator->get('handler_two');
}
// ...
}
If some service doesn't define the option/attribute configured in index_by
,
Symfony applies this fallback process:
- If the service class defines a static method called
getDefault<CamelCase index_by value>Name
(in this example,getDefaultKeyName()
), call it and use the returned value; - Otherwise, fall back to the default behavior and use the service ID.
The default_index_method
Option
This option defines the name of the service class method that will be called to get the value used to index the services:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
// src/CommandBus.php
namespace App;
use Symfony\Component\DependencyInjection\Attribute\TaggedLocator;
use Symfony\Component\DependencyInjection\ServiceLocator;
class CommandBus
{
public function __construct(
#[TaggedLocator('app.handler', defaultIndexMethod: 'getLocatorKey')]
ServiceLocator $locator
) {
}
}
If some service class doesn't define the method configured in default_index_method
,
Symfony will fall back to using the service ID as its index inside the locator.
Combining the index_by
and default_index_method
Options
You can combine both options in the same locator. Symfony will process them in the following order:
- If the service defines the option/attribute configured in
index_by
, use it; - If the service class defines the method configured in
default_index_method
, use it; - Otherwise, fall back to using the service ID as its index inside the locator.
Service Subscriber Trait
The ServiceSubscriberTrait provides an
implementation for ServiceSubscriberInterface
that looks through all methods in your class that are marked with the
SubscribedService attribute. It
provides a ServiceLocator
for the services of each method's return type.
The service id is __METHOD__
. This allows you to add dependencies to your
services based on type-hinted helper methods:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
// src/Service/MyService.php
namespace App\Service;
use Psr\Log\LoggerInterface;
use Symfony\Component\Routing\RouterInterface;
use Symfony\Contracts\Service\Attribute\SubscribedService;
use Symfony\Contracts\Service\ServiceSubscriberInterface;
use Symfony\Contracts\Service\ServiceSubscriberTrait;
class MyService implements ServiceSubscriberInterface
{
use ServiceSubscriberTrait;
public function doSomething()
{
// $this->router() ...
// $this->logger() ...
}
#[SubscribedService]
private function router(): RouterInterface
{
return $this->container->get(__METHOD__);
}
#[SubscribedService]
private function logger(): LoggerInterface
{
return $this->container->get(__METHOD__);
}
}
This allows you to create helper traits like RouterAware, LoggerAware, etc... and compose your services with them:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
// src/Service/LoggerAware.php
namespace App\Service;
use Psr\Log\LoggerInterface;
use Symfony\Contracts\Service\Attribute\SubscribedService;
trait LoggerAware
{
#[SubscribedService]
private function logger(): LoggerInterface
{
return $this->container->get(__CLASS__.'::'.__FUNCTION__);
}
}
// src/Service/RouterAware.php
namespace App\Service;
use Symfony\Component\Routing\RouterInterface;
use Symfony\Contracts\Service\Attribute\SubscribedService;
trait RouterAware
{
#[SubscribedService]
private function router(): RouterInterface
{
return $this->container->get(__CLASS__.'::'.__FUNCTION__);
}
}
// src/Service/MyService.php
namespace App\Service;
use Symfony\Contracts\Service\ServiceSubscriberInterface;
use Symfony\Contracts\Service\ServiceSubscriberTrait;
class MyService implements ServiceSubscriberInterface
{
use ServiceSubscriberTrait, LoggerAware, RouterAware;
public function doSomething()
{
// $this->router() ...
// $this->logger() ...
}
}
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.
5.4
Defining your subscribed service methods with the SubscribedService attribute was added in Symfony 5.4. Previously, any methods with no arguments and a return type were subscribed. This still works in 5.4 but is deprecated (only when using PHP 8) and will be removed in 6.0.
Testing a Service Subscriber
To unit test a service subscriber, you can create a fake ServiceLocator
:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
use Symfony\Component\DependencyInjection\ServiceLocator;
$container = new class() extends ServiceLocator {
private $services = [];
public function __construct()
{
parent::__construct([
'foo' => function () {
return $this->services['foo'] = $this->services['foo'] ?? new stdClass();
},
'bar' => function () {
return $this->services['bar'] = $this->services['bar'] ?? $this->createBar();
},
]);
}
private function createBar()
{
$bar = new stdClass();
$bar->foo = $this->get('foo');
return $bar;
}
};
$serviceSubscriber = new MyService($container);
// ...
Another alternative is to mock it using PHPUnit
:
1 2 3 4 5 6 7 8 9 10 11 12 13
use Psr\Container\ContainerInterface;
$container = $this->createMock(ContainerInterface::class);
$container->expects(self::any())
->method('get')
->willReturnMap([
['foo', $this->createStub(Foo::class)],
['bar', $this->createStub(Bar::class)],
])
;
$serviceSubscriber = new MyService($container);
// ...