我尝试使用我的包中的 prependExtensionConfig 将配置数组添加到不同的包。一切正常,直到 $config 被硬编码。
我的目标是使用 加载 $config 值服务 (例如来自数据库),而不是将其添加到另一个捆绑包中。
问题是当时没有加载服务。
我猜这是 symfony2 的一个限制。
有任何想法吗?谢谢
class MyExtension extends Extension implements PrependExtensionInterface
{
/**
* {@inheritDoc}
*/
public function load(array $configs, ContainerBuilder $container)
{
$configuration = new Configuration();
$config = $this->processConfiguration($configuration, $configs);
$loader = new Loader\YamlFileLoader($container, new FileLocator(__DIR__ . '/../Resources/config'));
$loader->load('services.yml');
}
public function prepend(ContainerBuilder $container)
{
$config = // load config from a service ...
$container->prependExtensionConfig('other_bundle', $config);
}
}
最佳答案
首先,您需要设置配置以从服务容器的参数部分获取值:
# app/config/config.yml
namespace:
subnamespace:
param1: %param1%
param2: %param2%
那你需要填写
%param1%
和 %param2%
容器中的参数与数据库中的值。为此,您需要声明您的 CompilerPass 并将其添加到容器中。加载整个容器后(在编译时),您将可以访问其中的所有服务。只需获取实体管理器服务并查询所需参数并将它们注册到容器中即可。
# src/Acme/YourBundle/DependencyInjection/Compiler/ParametersCompilerPass.php
class ParametersCompilerPass implements CompilerPassInterface
{
public function process(ContainerBuilder $container)
{
$em = $container->get('doctrine.orm.default_entity_manager');
$param1 = $em->getRepository('Acme:Params')->find(1);
$param2 = $em->getRepository('Acme:Params')->find(2);
$container->setParameter('param1', $param1);
$container->setParameter('param2', $param2);
}
}
# src/Acme/YourBundle/AcmeYourBundle.php
class AcmeYourBundle extends Bundle
{
public function build(ContainerBuilder $container)
{
parent::build($container);
$container->addCompilerPass(new ParametersCompilerPass(), PassConfig::TYPE_AFTER_REMOVING);
}
}
PassConfig::TYPE_AFTER_REMOVING
意味着这个 CompilerPass 几乎将在所有其他编译器通过之后被处理,此时您已经注入(inject)了每个服务。 关于Symfony prependExtensionConfig 与来自服务的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29083018/