Manu Manu - 2 months ago 9
PHP Question

Access service definition from previous bundle in extension

I have two bundles A and B that are loaded in AppKernel.php (first A, then B).

Configuration 1 (works)

Bundle A, Extension:

public function load(array $configs, ContainerBuilder $container)
{
$container->setParameter('test', '123');
}


Bundle B, Extension:

public function load(array $configs, ContainerBuilder $container)
{
$test = $container->getParameter('test');
}


Configuration 2 (works not)

Bundle A, Extension:

public function load(array $configs, ContainerBuilder $container)
{
$loader = new YamlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config'));
$loader->load('services.yml');
}


Bundle B, Extension:

public function load(array $configs, ContainerBuilder $container)
{
$def = $container->findDefinition('test_service');
}


So my question is why can I access parameters from a previous loaded bundle but not the service definitions? I know there are compiler passes, but I want to add some method calls to a definition without setting a parameter first.

Answer

No matter the order in which bundles are registered in AppKernel.php, because in the load() method doesn't get the actual container instance, but a copy. This container only has the parameters from the actual container (not service definition from others bundle/extension). So you should seems this exception message:

You have requested a non-existent service "test_service".

After loading the copy will be merged into the actual container. More details.


However, you can do it in other place, only needs to implement PrependExtensionInterface:

class BExtension extends Extension implements PrependExtensionInterface
{
    public function prepend(ContainerBuilder $container)
    {
        $def = $container->findDefinition('test_service');
    }
}

Inside the prepend() method, you have full access to the ContainerBuilder instance just before the load() method is called on each of the registered bundle Extensions. So you can play with external bundle definitions there. More details.

Comments