Symfony: how to get all services and related classes

What I'm trying to achieve is the following: Some of the services in my application contain a special annotation. Later, during the build process, a special team should find all the files with this annotation.

My approach is to download all packages first:

$container = $this->getContainer();

foreach ($container->getParameter('kernel.bundles') as $alias => $namespace)
    $bundle = $container->get('kernel')->getBundle($alias);

I am stuck at this point. How do I get a copy $bundleto tell me its services?

Note. I would also be pleased with a solution that is not related to the package, that is, one that downloads all available service definitions. ContainerBuildergot getDefinitionsone that looks promising, although I don't know how to access it from the team.

I need to get a list with service identifiers and their classes - especially classes, because these are the ones I need to load into the annotation reader.

Obviously, I don't want to parse myself services.yml, and Id would also like to avoid loading an instance of each service from $container->getServiceIds().

(Btw, tagged services do not help, I need annotations. And I want to automatically detect annotated services because tagging them will require an additional step that is unnecessary and error prone.)

+4
source share
2 answers

. . , .

, , , .

<?php

use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\Reference;

class RegisterClassNamesPass implements CompilerPassInterface
{
    public function process(ContainerBuilder $container)
    {
        if (!$container->has('app.class_names_manager')) {
            return;
        }

        $manager = $container->findDefinition(
            'app.class_names_manager'
        );

        foreach ($container->getDefinitions() as $id => $definition) {
            $class = $container->getParameterBag()->resolveValue($def->getClass());

            $definition->addMethodCall(
                'addClassName',
                array($id, $class)
            );
        }
    }
}
+3

, Ive getServiceIds:

$container = $this->getContainer();

foreach ($container->getServiceIds() as $id)
{
    $service = $container->get($id, $container::IGNORE_ON_INVALID_REFERENCE);
    if (!$service) continue;

    $class = get_class($service);

    // ...
}
+2

Source: https://habr.com/ru/post/1613889/


All Articles