Skip to content

[DependencyInjection] ServiceSubscriberTrait does not allow non-service "getter" methods #42217

@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

      pFad - Phonifier reborn

      Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

      Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


      Alternative Proxies:

      Alternative Proxy

      pFad Proxy

      pFad v3 Proxy

      pFad v4 Proxy