8000 [DI] Add section about service locators by chalasr · Pull Request #7458 · symfony/symfony-docs · GitHub
[go: up one dir, main page]

Skip to content
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
Rewords
  • Loading branch information
javiereguiluz authored Apr 28, 2017
commit f5e49424a9a161f1ad757f69bb45a0ffe16e8c3a
62 changes: 29 additions & 33 deletions service_container/service_locators.rst
3C59
Original file line number Diff line number Diff line change
Expand Up @@ -4,18 +4,15 @@
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
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 :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::
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::

// ...
class CommandBus
Expand Down Expand Up @@ -45,11 +42,9 @@ class names and use them to handle their respective command when it is asked for
// ...
$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::
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;

Expand All @@ -74,20 +69,19 @@ dependency injection container::
}
}

But injecting the container has many drawbacks including:
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.

- 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 predefined services while instantiating them only when actually needed.

Service Locators are intended to solve this problem by giving access to a set of
identified services while instantiating them only when really needed.
Defining a Service Locator
--------------------------

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:
First, define a new service for the service locator. Use its ``arguments``
option to include as many services as needed to it and add the
``container.service_locator`` tag to turn it into a service locator:

.. configuration-block::

Expand Down Expand Up @@ -138,11 +132,10 @@ tag:

.. note::

The services defined in the service locator argument must be keyed.
Those keys become their unique identifier inside the locator.

The services defined in the service locator argument must include keys,
which later become their unique identifiers inside the locator.

Now you can use it in your services by injecting it as needed:
Now you can use the service locator injecting it in any other service:

.. configuration-block::

Expand Down Expand Up @@ -183,13 +176,14 @@ Now you can use it in your services by injecting it as needed:

.. tip::

You should create and inject the service locator as an anonymous service if
it is not intended to be used by multiple services
If the service locator is not intended to be used by multiple services, it's
better to create and inject it as an anonymous service.

Usage
-----

Back to our CommandBus which now looks like::
Back to the previous CommandBus example, it looks like this when using the
service locator::

// ...
use Psr\Container\ContainerInterface;
Copy link
Contributor

Choose a reason for hiding this comment

The 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?

$this->psr11->get(get_class($command)) makes me think that Foo\RegisterUser is a service name, but semantically it isn't.

Copy link
Member Author

Choose a reason for hiding this comment

The 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

Copy link
Contributor

Choose a reason for hiding this comment

The 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 Map: you need some generic explicit interface, with NotFound* exception and get/has methods, but PHP doesn't have it (ArrayAccess is kinda similar, though), so here we go.

Yes, PSR-11 maps string on object, but semantically string here is not serviceId, but something more generic. It looks like far-fetched concept here.

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.

Copy link
Member Author

Choose a reason for hiding this comment

The 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).
I find the callable typehint useful for cases where there's no DIC behind the locator, which should not be the main usage of this feature to me since it is first built to avoid container-aware stuff inside the symfony full stack.

semantically string here is not serviceId, but something more generic. It looks like far-fetched concept here.

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.
Redefining identifiers might just be useful in some cases that I'm still not sure to get, but it seemed logic for others so here we are.

Second example with callable looks for me better even if it has implicit interface. At least, it has nothing to do with DI-containers.

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 Object[Store|Provider|Locator|Registry] instead of Container.

Expand Down Expand Up @@ -225,3 +219,5 @@ which implements the PSR-11 ``ContainerInterface``, but it is also a callable::
$handler = $locateHandler($commandClass);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why not only $handler = $this->locateHandler($commandClass);?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I guess you mean $this->handlerLocator($commandClass) :).
Anyway, the intermediate variable is mandatory, calling $this->handlerLocator() would make the engine look for a handlerLocator() method instead of executing the property as a callable.

Copy link
Contributor

Choose a reason for hiding this comment

The 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.
But as of PHP7, it could be $handler = ($this->handlerLocator)($commandClass)

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Indeed, good to know. Let's stay simple there though

Copy link
Contributor

Choose a reason for hiding this comment

The 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 😄 )

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ok guys, thanks!


return $handler->handle($command);

.. _`Command pattern`: https://en.wikipedia.org/wiki/Command_pattern
0