-
-
Notifications
You must be signed in to change notification settings - Fork 5.2k
[DI] Add section about service locators #7458
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Changes from 1 commit
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,227 @@ | ||
.. index:: | ||
single: DependencyInjection; Service Locators | ||
|
||
Service Locators | ||
================ | ||
|
||
What is a Service Locator | ||
------------------------- | ||
|
||
Sometimes, a service needs the ability to access other services without being sure | ||
that all of them will actually be used. | ||
|
||
In such cases, you may want the instantiation of these services to be lazy, that is | ||
not possible using explicit dependency injection since services are not all meant to | ||
be ``lazy`` (see :doc:`/service_container/lazy_services`). | ||
|
||
A real-world example being a CommandBus which maps command handlers by Command | ||
class names and use them to handle their respective command when it is asked for:: | ||
|
||
// ... | ||
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()); | ||
|
||
Because only one command is handled at a time, other command handlers are not | ||
used but unnecessarily instantiated. | ||
|
||
A solution allowing to keep handlers lazily loaded could be to inject the whole | ||
dependency injection container:: | ||
|
||
use Symfony\Component\DependencyInjection\ContainerInterface; | ||
|
||
class CommandBus | ||
{ | ||
private $container; | ||
|
||
public function __construct(ContainerInterface $container) | ||
{ | ||
$this->container = $container; | ||
} | ||
|
||
public function handle(Command $command) | ||
{ | ||
$commandClass = get_class($command) | ||
|
||
if ($this->container->has($commandClass)) { | ||
$handler = $this->container->get($commandClass); | ||
|
||
return $handler->handle($command); | ||
} | ||
} | ||
} | ||
|
||
But injecting the container has many drawbacks including: | ||
|
||
- too broad access to existing services | ||
- services which are actually useful are hidden | ||
|
||
Service Locators are intended to solve this problem by giving access to a set of | ||
identified services while instantiating them only when really needed. | ||
|
||
Configuration | ||
------------- | ||
|
||
For injecting a service locator into your service(s), you first need to register | ||
the service locator itself as a service using the `container.service_locator` | ||
tag: | ||
|
||
.. configuration-block:: | ||
|
||
.. code-block:: yaml | ||
|
||
services: | ||
|
||
app.command_handler_locator: | ||
class: Symfony\Component\DependencyInjection\ServiceLocator | ||
arguments: | ||
AppBundle\FooCommand: '@app.command_handler.foo' | ||
AppBundle\BarCommand: '@app.command_handler.bar' | ||
tags: ['container.service_locator'] | ||
|
||
.. code-block:: xml | ||
|
||
<?xml version="1.0" encoding="UTF-8" ?> | ||
<container xmlns="http://symfony.com/schema/dic/services" | ||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" | ||
xsi:schemaLocation="http://symfony.com/schema/dic/services http://symfony.com/schema/dic/services/services-1.0.xsd"> | ||
|
||
<services> | ||
|
||
<service id="app.command_handler_locator" class="Symfony\Component\DependencyInjection\ServiceLocator"> | ||
<argument key="AppBundle\FooCommand" type="service" id="app.command_handler.foo" /> | ||
<argument key="AppBundle\BarCommand" type="service" id="app.command_handler.bar" /> | ||
<tag name="container.service_locator" /> | ||
</service> | ||
|
||
</services> | ||
</container> | ||
|
||
.. code-block:: php | ||
|
||
use Symfony\Component\DependencyInjection\ServiceLocator; | ||
use Symfony\Component\DependencyInjection\Reference; | ||
|
||
//... | ||
|
||
$container | ||
->register('app.command_handler_locator', ServiceLocator::class) | ||
->addTag('container.service_locator') | ||
->setArguments(array( | ||
'AppBundle\FooCommand' => new Reference('app.command_handler.foo'), | ||
'AppBundle\BarCommand' => new Reference('app.command_handler.bar'), | ||
)) | ||
; | ||
|
||
.. note:: | ||
|
||
The services defined in the service locator argument must be keyed. | ||
Those keys become their unique identifier inside the locator. | ||
|
||
|
||
Now you can use it in your services by injecting it as needed: | ||
|
||
.. configuration-block:: | ||
|
||
.. code-block:: yaml | ||
|
||
services: | ||
|
||
AppBundle\CommandBus: | ||
arguments: ['@app.command_handler_locator'] | ||
|
||
.. code-block:: xml | ||
|
||
<?xml version="1.0" encoding="UTF-8" ?> | ||
<container xmlns="http://symfony.com/schema/dic/services" | ||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" | ||
xsi:schemaLocation="http://symfony.com/schema/dic/services http://symfony.com/schema/dic/services/services-1.0.xsd"> | ||
|
||
<services> | ||
|
||
<service id="AppBundle\CommandBus"> | ||
<argument type="service" id="app.command_handler.locator" /> | ||
</service> | ||
|
||
</services> | ||
</container> | ||
|
||
.. code-block:: php | ||
|
||
use AppBundle\CommandBus; | ||
use Symfony\Component\DependencyInjection\Reference; | ||
|
||
//... | ||
|
||
$container | ||
->register(CommandBus::class) | ||
->setArguments(array(new Reference('app.command_handler_locator'))) | ||
; | ||
|
||
.. tip:: | ||
|
||
You should create and inject the service locator as an anonymous service if | ||
it is not intended to be used by multiple services | ||
|
||
Usage | ||
----- | ||
|
||
Back to our CommandBus which now looks like:: | ||
|
||
// ... | ||
use Psr\Container\ContainerInterface; | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Why do you type hint against this interface? Simple closure is enough, isn't it?
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Goal is to show the provided PSR-11 implem first, so it's clear what you can do when receiving such argument, including throwable exceptions. Just below there's an example showing that it can be used as a callable and how it can be used There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I'm not even sure that PSR-11 makes sense for this feature at all. In this context PSR-11 looks like a replacement for the Java's Yes, PSR-11 maps I can't imagine case when I need to type hint against the PSR-11 interface unless I really do something highly cohesive with DI-containers, where I want to say explicitly: "yes, this is about DI-containers", e.g. decorator for DI-containers which logs service ids. Second example with callable looks for me better even if it has implicit interface. At least, it has nothing to do with DI-containers. So the example with PSR-11 interface looks a bit unnatural for me. Probably, it's just me. Just my 5 cents. There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Yet I understand your concerns, I think PSR-11 is legit in this context since the primary goal of the locator is to fetch services from the DIC (keeping in mind that this doc is about symfony/DI).
In my opinion, services identifiers should remain the same in the locator than in the container from which they come from, so they're safely accessible no matter which container/registry/locator/provider is given to you, that is primordial to me.
As you pointed out in the code PR, container is just a kind of map after all and if you ask me, PSR-11 could be called |
||
|
||
class CommandBus | ||
{ | ||
/** | ||
* @var ContainerInterface | ||
*/ | ||
private $handlerLocator; | ||
|
||
// ... | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. You may write the constructor here to understand the correlation between the service declaration and the class instanciation There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. You're right, definitely needed for a good understanding. |
||
|
||
public function handle(Command $command) | ||
{ | ||
$commandClass = get_class($command); | ||
|
||
if (!$this->handlerLocator->has($commandClass)) { | ||
return; | ||
} | ||
|
||
$handler = $this->handlerLocator->get($commandClass); | ||
|
||
return $handler->handle($command); | ||
} | ||
} | ||
|
||
The injected service is an instance of :class:`Symfony\\Component\\DependencyInjection\\ServiceLocator` | ||
which implements the PSR-11 ``ContainerInterface``, but it is also a callable:: | ||
|
||
// ... | ||
$locateHandler = $this->handlerLocator; | ||
$handler = $locateHandler($commandClass); | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Why not only There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I guess you mean There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. The intermediate variable assignment is necessary for php to understand it's a callable property, and not a method. There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Indeed, good to know. Let's stay simple there though There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. (But this is documentation. I think the current code sample is great for this purpose 😄 ) There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Ok guys, thanks! |
||
|
||
return $handler->handle($command); |
Uh oh!
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I recently implemented a service locator for API Platform and the syntax described here is currently not the correct one.
According to src/Symfony/Component/DependencyInjection/Compiler/ServiceLocatorTagPass.php#L40-L42, this should be:
Same for the YAML/XML config.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Indeed, fixed. Thanks!