Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access service definition from previous bundle in extension

Tags:

php

symfony

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.

like image 501
Manu Avatar asked Dec 02 '25 10:12

Manu


1 Answers

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.

like image 183
yceruto Avatar answered Dec 05 '25 01:12

yceruto



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!