-
-
Notifications
You must be signed in to change notification settings - Fork 9.6k
[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
Conversation
@@ -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)) { |
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.
shouldn't it be AutowirableReference
?
|
||
$serviceMap = array(); | ||
|
||
foreach ($services as $services) { |
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.
$services
looks undefined here
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.
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); |
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.
shouldn't you validate that the type is still not empty here ? ``?```alone should be forbidden too.
|
||
namespace Symfony\Component\DependencyInjection; | ||
|
||
Psr\Container\ContainerInterface; |
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.
missing use
@@ -21,7 +23,7 @@ | |||
* | |||
* @experimental in version 3.3 | |||
*/ | |||
class ServiceLocatorArgument implements ArgumentInterface | |||
class ServiceLocatorArgument extends Definition implements ArgumentInterface |
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.
won't this cause issues with recursive passes processing Definition objects ? Is it really a Definition ?
Talking with others, it looks like this approach has a drawback: it does not play well with composition. |
return new Reference($this->serviceLocator); | ||
} | ||
|
||
if (!$value instanceof Definition || $value->isAbstract() || $value->isSynthetic() || !$value->hasTag('kernel.service_subscriber')) { |
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.
should be added to UnusedTagsPass::$whitelist
b5ab5d1
to
6c8f067
Compare
a887059
to
040df3d
Compare
PR rebased and ready Status: needs review |
f5cfdf0
to
70cc3c5
Compare
Just added a few more test cases. |
As you can see, this allows having type-hinted service locators also, on top of explicit deps. |
5e30b79
to
8f830e6
Compare
8f830e6
to
0d917b3
Compare
0d917b3
to
c5e80a2
Compare
|
||
foreach ($value->getTag('container.service_subscriber') as $attributes) { | ||
if (!$attributes) { | ||
continue; |
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.
Shoudn't we throw an exception instead?
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.
When there is not attributes at all, L75 creates "TypedReference" that target the service that has the same name as the type
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.
👍
Thank you @nicolas-grekas. |
…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
…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
…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, | ||
); | ||
} |
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.
@nicolas-grekas The service definition has not been updated (not tagged container.service_subscriber
) so this is actually unused, is it expected?
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.
Expected: getParameter is used, so cannot by a PSR11 container.
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.
Yes ok, I was wondering if you still did it on purpose.
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:
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:
The benefits are:
Some might argue that: