8000 [DependencyInjection] `ServiceSubscriberTrait` does not allow non-service "getter" methods · Issue #42217 · symfony/symfony · GitHub
[go: up one dir, main page]

Skip to content
[DependencyInjection] ServiceSubscriberTrait does not allow non-service "getter" methods #42217
Closed
@kbond

Description

@kbond

Symfony version(s) affected: 4.2+

Description
When using the ServiceSubscriberTrait, you cannot have methods with no arguments and a class return type that cannot be created as a service. Memoization of a value object/model is a common use-case that would create this problem.

This issue was brought to my attention by @weaverryan who had this issue in a real app.

How to reproduce
https://github.com/kbond/subscriber-trait-bug-reproducer is a reproducer. Clone and run composer install && bin/console lint:container to see the exception. This is the method that causes the problem.

Possible Solution
My initial proposal for this feature required users tag methods they want as services with a @service docblock tag. This was ultimately rejected but perhaps we could bring this idea back with attributes?

#[SubscribedService]
private function service1(): Service1
{
    return $this->container->get(__METHOD__);
}

#[SubscribedService('custom_name')]
private function service2(): Service2
{
    return $this->container->get('custom_name');
}

I'd suggest deprecating the current usage (no attribute) in 5.4 and requiring attributes in 6.0. I don't know how/if this would work with Symfony's BC policy seeing as attributes are PHP8+ and Symfony 5 requires 7.2...

Any other ideas?

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions

      0