Skip to content

[DI] Add and wire ServiceSubscriberInterface - aka explicit service locators #21708

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

Merged
merged 2 commits into from
Mar 22, 2017

Conversation

nicolas-grekas
Copy link
Member

@nicolas-grekas nicolas-grekas commented Feb 21, 2017

Q A
Branch? master
Bug fix? no
New feature? yes
BC breaks? no
Deprecations? no
Tests pass? no test yet
Fixed tickets #20658
License MIT
Doc PR -

This PR implements the second and missing part of #20658: it enables objects to declare their service dependencies in a similar way than we do for EventSubscribers: via a static method. Here is the interface and its current description:

namespace Symfony\Component\DependencyInjection;

/**
 * A ServiceSubscriber exposes its dependencies via the static {@link getSubscribedServices} method.
 *
 * The getSubscribedServices method returns an array of service types required by such instances,
 * optionally keyed by the service names used internally. Service types that start with an interrogation
 * mark "?" are optional, while the other ones are mandatory service dependencies.
 *
 * The injected service locators SHOULD NOT allow access to any other services not specified by the method.
 *
 * It is expected that ServiceSubscriber instances consume PSR-11-based service locators internally.
 * This interface does not dictate any injection method for these service locators, although constructor
 * injection is recommended.
 *
 * @author Nicolas Grekas <p@tchwork.com>
 */
interface ServiceSubscriberInterface
{
    /**
     * Returns an array of service types required by such instances, optionally keyed by the service names used internally.
     *
     * For mandatory dependencies:
     *
     *  * array('logger' => 'Psr\Log\LoggerInterface') means the objects use the "logger" name
     *    internally to fetch a service which must implement Psr\Log\LoggerInterface.
     *  * array('Psr\Log\LoggerInterface') is a shortcut for
     *  * array('Psr\Log\LoggerInterface' => 'Psr\Log\LoggerInterface')
     *
     * otherwise:
     *
     *  * array('logger' => '?Psr\Log\LoggerInterface') denotes an optional dependency
     *  * array('?Psr\Log\LoggerInterface') is a shortcut for
     *  * array('Psr\Log\LoggerInterface' => '?Psr\Log\LoggerInterface')
     *
     * @return array The required service types, optionally keyed by service names
     */
    public static function getSubscribedServices();
}

We could then have eg a controller-as-a-service implement this interface, and be auto or manually wired according to the return value of this method - using the "kernel.service_subscriber" tag to do so.
eg:

services:
  App\Controller\FooController:
    arguments: [ '@container' ]
    tags:
      - name: kernel.service_subscriber
        key: logger
        service: monolog.logger.foo_channel

The benefits are:

  • it keeps the lazy-behavior gained by service locators / container injection
  • it allows the referenced services to be made private from the pov of the main Symfony DIC - thus enables some compiler optimizations
  • it makes dependencies autowirable (while keeping manual wiring possible)
  • it does not add any strong coupling at the architecture level
  • and most importantly and contrary to regular container injection, it makes dependencies explicit - each classes declaring which services it consumes.

Some might argue that:

  • it requires to be explicit - thus more verbose. Yet many others think it's a good thing - ie it's worth it.
  • some coupling happens at the dependency level, since you need to get the DI component to get the interface definition. This is something that the PHP-FIG could address at some point.

@nicolas-grekas nicolas-grekas added this to the 3.3 milestone Feb 21, 2017
@nicolas-grekas nicolas-grekas changed the title [DI] Add and wire ServiceSubscriberInterface [DI] Add and wire ServiceSubscriberInterface - aka explicit service locators Feb 22, 2017
@@ -99,6 +99,10 @@ public static function createResourceForClass(\ReflectionClass $reflectionClass)
*/
protected function processValue($value, $isRoot = false)
{
if ($value instanceof AutowiredReference && ContainerInterface::EXCEPTION_ON_INVALID_REFERENCE !== $value->getInvalidBehavior() && $this->container->has((string) $value)) {
Copy link
Member

Choose a reason for hiding this comment

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

shouldn't it be AutowirableReference ?


$serviceMap = array();

foreach ($services as $services) {
Copy link
Member

Choose a reason for hiding this comment

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

$services looks undefined here

Copy link
Contributor

Choose a reason for hiding this comment

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

Plus, the array and the item are the same variable, I don't think this is wanted.

throw new InvalidArgumentException(sprintf('%s::getSubscribedServices() must return types as non-empty strings for service "%s" key "%s", "%s" returned.', $class, $this->currentId, $key, gettype($type)));
}
if ($isOptional = '?' === $type[0]) {
$type = substr($type, 1);
Copy link
Member

Choose a reason for hiding this comment

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

shouldn't you validate that the type is still not empty here ? ``?```alone should be forbidden too.


namespace Symfony\Component\DependencyInjection;

Psr\Container\ContainerInterface;
Copy link
Member

Choose a reason for hiding this comment

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

missing use

@@ -21,7 +23,7 @@
*
* @experimental in version 3.3
*/
class ServiceLocatorArgument implements ArgumentInterface
class ServiceLocatorArgument extends Definition implements ArgumentInterface
Copy link
Member

Choose a reason for hiding this comment

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

won't this cause issues with recursive passes processing Definition objects ? Is it really a Definition ?

@nicolas-grekas
Copy link
Member Author

nicolas-grekas commented Feb 22, 2017

Talking with others, it looks like this approach has a drawback: it does not play well with composition.
Say you have a class that uses trait1 and trait2, then the deps declaration can't be provided by each trait because of method name collision. Instead, the class itself must do it.
That's an issue getter does not have. use trait1 and trait2 which declares their deps via eg abstract getters, and composition is at its best.

return new Reference($this->serviceLocator);
}

if (!$value instanceof Definition || $value->isAbstract() || $value->isSynthetic() || !$value->hasTag('kernel.service_subscriber')) {
Copy link
Member

Choose a reason for hiding this comment

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

should be added to UnusedTagsPass::$whitelist

@nicolas-grekas nicolas-grekas force-pushed the di-subscriber branch 2 times, most recently from b5ab5d1 to 6c8f067 Compare February 27, 2017 14:17
@nicolas-grekas nicolas-grekas force-pushed the di-subscriber branch 7 times, most recently from a887059 to 040df3d Compare March 5, 2017 21:22
@nicolas-grekas
Copy link
Member Author

PR rebased and ready

Status: needs review

@nicolas-grekas
Copy link
Member Author

Just added a few more test cases.

@nicolas-grekas
Copy link
Member Author

As you can see, this allows having type-hinted service locators also, on top of explicit deps.
Can only help write more robust code and help IDEs provide auto-completion.

@nicolas-grekas nicolas-grekas force-pushed the di-subscriber branch 3 times, most recently from 5e30b79 to 8f830e6 Compare March 16, 2017 15:32

foreach ($value->getTag('container.service_subscriber') as $attributes) {
if (!$attributes) {
continue;
Copy link
Member

Choose a reason for hiding this comment

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

Shoudn't we throw an exception instead?

Copy link
Member Author

Choose a reason for hiding this comment

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

When there is not attributes at all, L75 creates "TypedReference" that target the service that has the same name as the type

Copy link
Member

Choose a reason for hiding this comment

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

👍

@fabpot
Copy link
Member

fabpot commented Mar 22, 2017

Thank you @nicolas-grekas.

@fabpot fabpot merged commit c5e80a2 into symfony:master Mar 22, 2017
fabpot added a commit that referenced this pull request Mar 22, 2017
…licit service locators (nicolas-grekas)

This PR was squashed before being merged into the 3.3-dev branch (closes #21708).

Discussion
----------

[DI] Add and wire ServiceSubscriberInterface - aka explicit service locators

| Q             | A
| ------------- | ---
| Branch?       | master
| Bug fix?      | no
| New feature?  | yes
| BC breaks?    | no
| Deprecations? | no
| Tests pass?   | no test yet
| Fixed tickets | #20658
| License       | MIT
| Doc PR        | -

This PR implements the second and missing part of #20658: it enables objects to declare their service dependencies in a similar way than we do for EventSubscribers: via a static method. Here is the interface and its current description:
```php
namespace Symfony\Component\DependencyInjection;

/**
 * A ServiceSubscriber exposes its dependencies via the static {@link getSubscribedServices} method.
 *
 * The getSubscribedServices method returns an array of service types required by such instances,
 * optionally keyed by the service names used internally. Service types that start with an interrogation
 * mark "?" are optional, while the other ones are mandatory service dependencies.
 *
 * The injected service locators SHOULD NOT allow access to any other services not specified by the method.
 *
 * It is expected that ServiceSubscriber instances consume PSR-11-based service locators internally.
 * This interface does not dictate any injection method for these service locators, although constructor
 * injection is recommended.
 *
 * @author Nicolas Grekas <p@tchwork.com>
 */
interface ServiceSubscriberInterface
{
    /**
     * Returns an array of service types required by such instances, optionally keyed by the service names used internally.
     *
     * For mandatory dependencies:
     *
     *  * array('logger' => 'Psr\Log\LoggerInterface') means the objects use the "logger" name
     *    internally to fetch a service which must implement Psr\Log\LoggerInterface.
     *  * array('Psr\Log\LoggerInterface') is a shortcut for
     *  * array('Psr\Log\LoggerInterface' => 'Psr\Log\LoggerInterface')
     *
     * otherwise:
     *
     *  * array('logger' => '?Psr\Log\LoggerInterface') denotes an optional dependency
     *  * array('?Psr\Log\LoggerInterface') is a shortcut for
     *  * array('Psr\Log\LoggerInterface' => '?Psr\Log\LoggerInterface')
     *
     * @return array The required service types, optionally keyed by service names
     */
    public static function getSubscribedServices();
}
```

We could then have eg a controller-as-a-service implement this interface, and be auto or manually wired according to the return value of this method - using the "kernel.service_subscriber" tag to do so.
eg:

```yaml
services:
  App\Controller\FooController:
    arguments: [service_container]
    tags:
      - name: kernel.service_subscriber
        key: logger
        service: monolog.logger.foo_channel
```

The benefits are:
- it keeps the lazy-behavior gained by service locators / container injection
- it allows the referenced services to be made private from the pov of the main Symfony DIC - thus enables some compiler optimizations
- it makes dependencies autowirable (while keeping manual wiring possible)
- it does not add any strong coupling at the architecture level
- and most importantly and contrary to regular container injection, *it makes dependencies explicit* - each classes declaring which services it consumes.

Some might argue that:
- it requires to be explicit - thus more verbose. Yet many others think it's a good thing - ie it's worth it.
- some coupling happens at the dependency level, since you need to get the DI component to get the interface definition. This is something that the PHP-FIG could address at some point.

Commits
-------

c5e80a2 implement ServiceSubscriberInterface where applicable
9b7df39 [DI] Add and wire ServiceSubscriberInterface
@nicolas-grekas nicolas-grekas deleted the di-subscriber branch March 22, 2017 20:24
fabpot added a commit that referenced this pull request Mar 25, 2017
…ing ControllerTrait (nicolas-grekas)

This PR was merged into the 3.3-dev branch.

Discussion
----------

[FrameworkBundle] Introduce AbstractController, replacing ControllerTrait

| Q             | A
| ------------- | ---
| Branch?       | master
| Bug fix?      | no
| New feature?  | yes
| BC breaks?    | no (master only)
| Deprecations? | yes
| Tests pass?   | yes
| Fixed tickets | -
| License       | MIT
| Doc PR        | -

Basically reverts and replaces #18193.

Instead of using getter injection to provide our controller helpers, let's leverage the new `ServiceSubscriberInterface` (see #21708).
This is what the proposed `AbstractController` class provides.

So, instead of extending `Controller`, this would encourage extending `AbstractController`.
This provides almost the same experience, but makes the container private, thus not usable by userland (this safeguard was already provided by `ControllerTrait`).

I did not deprecate `Controller`, but I think we should. Now that we also have "controller.service_arguments" (see #21771), we have everything in place to encourage *not* using the container in controllers directly anymore.

My target in doing so is removing getter injection, which won't have any use case in core anymore.

The wiring for this could be:

```yaml
services:
    _instanceof:
        Symfony\Bundle\FrameworkBundle\Controller\AbstractController:
            calls: [ [ setContainer, [ '@container' ] ] ]
            tags: [ container.service_subscriber ]
````

But this is optional, because we don't really need to inject a scoped service locator: injecting the real container is fine also, since everything is private. And this is done automatically on ControllerResolver.

Commits
-------

a93f059 [FrameworkBundle] Introduce AbstractController, replacing ControllerTrait
fabpot added a commit that referenced this pull request Mar 25, 2017
…las-grekas)" (nicolas-grekas)

This PR was merged into the 3.3-dev branch.

Discussion
----------

Revert "feature #20973 [DI] Add getter injection (nicolas-grekas)"

This reverts commit 2183f98, reversing
changes made to b465634.

| Q             | A
| ------------- | ---
| Branch?       | master
| Bug fix?      | no
| New feature?  | yes
| BC breaks?    | no (master only)
| Deprecations? | no
| Tests pass?   | yes
| Fixed tickets | -
| License       | MIT
| Doc PR        | -

Let's remove getter injection, we now have enough alternative mechanisms to achieve almost the same results (e.g. `ServiceSubscriberInterface`, see #21708)., and I'm tired being called by names because of it.

The only use case in core is `ControllerTrait`, but this should be gone if #22157 is merged.

Commits
-------

23fa3a0 Revert "feature #20973 [DI] Add getter injection (nicolas-grekas)"
return array(
'routing.loader' => LoaderInterface::class,
);
}
Copy link
Member

Choose a reason for hiding this comment

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

@nicolas-grekas The service definition has not been updated (not tagged container.service_subscriber) so this is actually unused, is it expected?

Copy link
Member Author

Choose a reason for hiding this comment

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

Expected: getParameter is used, so cannot by a PSR11 container.

Copy link
Member

Choose a reason for hiding this comment

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

Yes ok, I was wondering if you still did it on purpose.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

6 participants