diff --git a/service_container/service_locators.rst b/service_container/service_locators.rst index ac94f13552b..5471eef80a5 100644 --- a/service_container/service_locators.rst +++ b/service_container/service_locators.rst @@ -14,6 +14,9 @@ A real-world 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:: + // src/AppBundle/CommandBus.php + namespace AppBundle; + // ... class CommandBus { @@ -46,28 +49,29 @@ 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 whole dependency injection container:: - use Symfony\Component\DependencyInjection\ContainerInterface; + // ... + use Symfony\Component\DependencyInjection\ContainerInterface; - class CommandBus - { - private $container; + class CommandBus + { + private $container; - public function __construct(ContainerInterface $container) - { - $this->container = $container; - } + public function __construct(ContainerInterface $container) + { + $this->container = $container; + } - public function handle(Command $command) - { - $commandClass = get_class($command); + public function handle(Command $command) + { + $commandClass = get_class($command); - if ($this->container->has($commandClass)) { - $handler = $this->container->get($commandClass); + if ($this->container->has($commandClass)) { + $handler = $this->container->get($commandClass); - return $handler->handle($command); - } + return $handler->handle($command); } } + } However, injecting the entire container is discouraged because it gives too broad access to existing services and it hides the actual dependencies of the @@ -87,8 +91,8 @@ option to include as many services as needed to it and add the .. code-block:: yaml + // app/config/services.yml services: - app.command_handler_locator: class: Symfony\Component\DependencyInjection\ServiceLocator tags: ['container.service_locator'] @@ -99,6 +103,7 @@ option to include as many services as needed to it and add the .. code-block:: xml + - + @@ -167,11 +174,10 @@ Now you can use the service locator injecting it in any other service: .. code-block:: php + // app/config/services.php use AppBundle\CommandBus; use Symfony\Component\DependencyInjection\Reference; - //... - $container ->register(CommandBus::class) ->setArguments(array(new Reference('app.command_handler_locator'))) @@ -185,7 +191,7 @@ Now you can use the service locator injecting it in any other service: Usage ----- -Back to the previous CommandBus example, it looks like this when using the +Back to the previous ``CommandBus`` example, it looks like this when using the service locator:: // ...