Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

[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 ourterms of service andprivacy statement. We’ll occasionally send you account related emails.

Already on GitHub?Sign in to your account

Merged
fabpot merged 2 commits intosymfony:masterfromnicolas-grekas:di-subscriber
Mar 22, 2017

Conversation

@nicolas-grekas
Copy link
Member

@nicolas-grekasnicolas-grekas commentedFeb 21, 2017
edited
Loading

QA
Branch?master
Bug fix?no
New feature?yes
BC breaks?no
Deprecations?no
Tests pass?no test yet
Fixed tickets#20658
LicenseMIT
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:

namespaceSymfony\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     */publicstaticfunctiongetSubscribedServices();}

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_subscriberkey:loggerservice: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.

chalasr reacted with thumbs up emoji
@nicolas-grekasnicolas-grekas added this to the3.3 milestoneFeb 21, 2017
@nicolas-grekasnicolas-grekas changed the title[DI] Add and wire ServiceSubscriberInterface[DI] Add and wire ServiceSubscriberInterface - aka explicit service locatorsFeb 22, 2017
*/
protectedfunctionprocessValue($value,$isRoot =false)
{
if ($valueinstanceof 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 beAutowirableReference ?


$serviceMap =array();

foreach ($servicesas$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.

thrownewInvalidArgumentException(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.


namespaceSymfony\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.

missinguse

* @experimental in version 3.3
*/
class ServiceLocatorArgumentimplements ArgumentInterface
class ServiceLocatorArgumentextends Definitionimplements 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
MemberAuthor

nicolas-grekas commentedFeb 22, 2017
edited
Loading

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.

returnnewReference($this->serviceLocator);
}

if (!$valueinstanceof 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 toUnusedTagsPass::$whitelist

nicolas-grekas reacted with thumbs up emoji
@nicolas-grekasnicolas-grekasforce-pushed thedi-subscriber branch 2 times, most recently fromb5ab5d1 to6c8f067CompareFebruary 27, 2017 14:17
@nicolas-grekasnicolas-grekasforce-pushed thedi-subscriber branch 7 times, most recently froma887059 to040df3dCompareMarch 5, 2017 21:22
@nicolas-grekas
Copy link
MemberAuthor

PR rebased and ready

Status: needs review

@nicolas-grekas
Copy link
MemberAuthor

Just added a few more test cases.

@nicolas-grekas
Copy link
MemberAuthor

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.

sstok reacted with hooray emoji


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
MemberAuthor

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

Thank you@nicolas-grekas.

@fabpotfabpot merged commitc5e80a2 intosymfony:masterMar 22, 2017
fabpot added a commit that referenced this pull requestMar 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:```phpnamespace 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:```yamlservices:  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 applicable9b7df39 [DI] Add and wire ServiceSubscriberInterface
@nicolas-grekasnicolas-grekas deleted the di-subscriber branchMarch 22, 2017 20:24
fabpot added a commit that referenced this pull requestMar 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:```yamlservices:    _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 requestMar 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 commit2183f98, reversingchanges made tob465634.| 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)"
returnarray(
'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 taggedcontainer.service_subscriber) so this is actually unused, is it expected?

Copy link
MemberAuthor

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 freeto join this conversation on GitHub. Already have an account?Sign in to comment

Reviewers

@fabpotfabpotfabpot left review comments

@stofstofstof requested changes

@chalasrchalasrchalasr left review comments

+1 more reviewer

@soullivaneuhsoullivaneuhsoullivaneuh left review comments

Reviewers whose approvals may not affect merge requirements

Assignees

No one assigned

Projects

None yet

Milestone

3.3

Development

Successfully merging this pull request may close these issues.

6 participants

@nicolas-grekas@fabpot@stof@soullivaneuh@chalasr@carsonbot

[8]ページ先頭

©2009-2025 Movatter.jp