【问题标题】:Processing multiple Symfony bundle configs with one bundle用一个包处理多个 Symfony 包配置
【发布时间】:2015-10-30 22:49:10
【问题描述】:

我有很多捆绑包,它们在 BundleName/Resources/config/rules.yml 中保存了名为 rules.yml 的类似配置文件 每个配置文件都遵循相同的结构:

bundle_name:
    rules:
      name:
      items: []
      requirements: []

我有一个名为 RulerBundle 的捆绑包。这个包需要自动加载、验证和组合在其他包中找到的所有 rules.yml。我希望 RulerBundle 产生类似的东西:

bundle_a:
    rules:
      name: Rule 1
      items: ['First Item']
      requirements: ['Second Item', 'Third Item']
bundle_b:
    rules:
      name: Rule 2
      items: ['Second Item']
      requirements: ['Third Item']

当使用 rules.yml 添加新包时,这应该会自动更新

问题

  • 我应该验证和处理每个捆绑包中的配置吗?这将导致代码重复,因为验证规则相同。

  • 如何使用 RulerBundle 查找和合并每个捆绑配置

【问题讨论】:

  • 这可能对您有用:stackoverflow.com/a/33446045/1348344 我描述了如何以类似的方式使用资产配置。
  • @pfwd"我有很多捆绑包" - 您是在单个应用程序中获得所有这些,还是它们是独立于主应用程序的捆绑包?

标签: php symfony


【解决方案1】:

因此,您可以在顶层包中编写一个 DependencyInjection 扩展,该扩展将执行所有验证。不确定如果某些内容无效会发生什么,但您可以这样做:

// src/BundleName/DependencyInjection/BundleExtension.php
namespace Acme\HelloBundle\DependencyInjection;

use Symfony\Component\HttpKernel\DependencyInjection\Extension;
use Symfony\Component\DependencyInjection\Extension\PrependExtensionInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;

class BundleName extends Extension implements PrependExtensionInterface
{
    public function prepend(ContainerBuilder $container)
    {
        $bundles = $container->getParameter('kernel.bundles');
        foreach ($bundles as $name => $extension) {
            $loader = new Loader\YamlFileLoader($container, new FileLocator(__DIR__.$name.'/../../Resources/config'));
            // load the configuration file, returned as an array
            $config = $loader->loadFile('rules.yml');

            // validate the contents of your file
            $this->validateConfig($config);

            // append the config with the specified bundle name "bundle_a", "bundle_a"
            $container->prependExtensionConfig($name, $config);
        }
    }
}

还没有测试过这些,但通常这是基本想法。您需要实现配置验证方法。

【讨论】:

    猜你喜欢
    • 2022-06-18
    • 2018-02-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-24
    相关资源
    最近更新 更多