Processing multiple Symfony bundle configs with one bundle

时间:2015-10-30 22:49:10

标签: php symfony

I have lots of bundles which have similar config files called rules.yml held in BundleName/Resources/config/rules.yml Each config file follows the same structure:

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

I have one bundle called RulerBundle. This bundle needs to automatically load, validate and combine all the rules.yml found within the other bundles. I would like RulerBundle to produce something like:

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']

This should be automatically updated when a new bundle is added with a rules.yml

Questions

  • Should I validate and process the config within every bundle? This will lead to code duplication as the validation rules will just be same.

  • How would I go about finding and merging each of the bundle configs with the RulerBundle

1 个答案:

答案 0 :(得分:0)

因此,您可以在顶级包中编写一个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);
        }
    }
}

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