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