我在AppKernel.php中加载了两个bundle A和B(首先是A,然后是B)。
配置1 (works)
Bundle A,扩展:
public function load(array $configs, ContainerBuilder $container)
{
$container->setParameter('test', '123');
}
Bundle B,扩展:
public function load(array $configs, ContainerBuilder $container)
{
$test = $container->getParameter('test');
}
配置2(不工作)
Bundle A,扩展:
public function load(array $configs, ContainerBuilder $container)
{
$loader = new YamlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config'));
$loader->load('services.yml');
}
Bundle B,扩展:
public function load(array $configs, ContainerBuilder $container)
{
$def = $container->findDefinition('test_service');
}
所以我的问题是为什么我可以访问先前加载的bundle的参数,而不能访问服务定义?我知道有编译器传递,但我想添加一些方法调用到定义,而不需要先设置参数。
无论bundle在AppKernel.php
中注册的顺序如何,因为在load()
方法中没有获得实际的容器实例,而是获得的副本。这个容器只有来自实际容器的参数(没有来自其他bundle/扩展的服务定义)。所以你应该看到这个异常消息:
You have requested a non-existent service "test_service".
加载后,副本将合并到实际容器中。更多细节。
然而,你可以在其他地方做,只需要实现PrependExtensionInterface
:
class BExtension extends Extension implements PrependExtensionInterface
{
public function prepend(ContainerBuilder $container)
{
$def = $container->findDefinition('test_service');
}
}
在prepend()
方法中,在对每个已注册的bundle扩展调用load()
方法之前,您可以完全访问ContainerBuilder
实例。你可以在这里使用外部bundle定义。更多细节。