Skip to content

Services are not private if included through a Service Subscriber/Locator #219

@Pixelshaped

Description

@Pixelshaped

Since #211 there is no way to get Services on the container by default. This a nice idea but it overlooks legitimate use-cases: it is indeed possible to get services on the container without getting a deprecation warning if your service implements the ServiceSubscriberInterface for example (see docs: https://symfony.com/doc/current/service_container/service_subscribers_locators.html#defining-a-service-subscriber)

It's the preferred way to make loading of services lazy: "Sometimes, a service needs access to several other services without being sure that all of them will actually be used. In those cases, you may want the instantiation of the services to be lazy". If you want an official example, go look at AbstractController

Now this raises errors:

 ------ --------------------------------------------------------------------- 
  Line   src/Twig/CategoryExtension.php                                       
 ------ --------------------------------------------------------------------- 
  33     Service "App\Service\ProductCategoryHelper" is private.              
  33     Service "Symfony\Component\HttpFoundation\RequestStack" is private.  
 ------ --------------------------------------------------------------------- 
class CategoryExtension extends AbstractExtension implements ServiceSubscriberInterface
{
    public function __construct(
        private ContainerInterface $container
    ) {}

    public function getFunctions(): array
    {
        return [
            ... whole bunch of other functions ...
            new TwigFunction('get_category_tree', [$this, 'getCategoryTree']),
        ];
    }

    /**
     * @return Collection<int, Category>
     */
    public function getCategoryTree(): Collection
    {
        return $this->container->get(ProductCategoryHelper::class)->getCategoryTree($this->container->get(RequestStack::class)->getCurrentRequest()->getLocale());
    }

    /**
     * @return array<string>
     */
    public static function getSubscribedServices(): array
    {
        return [
            ProductCategoryHelper::class,
            RequestStack::class
        ];
    }
}

But really, it shouldn't.

@jeroennoten

Current Symfony version: 5.4.1

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions