使用一个包处理多个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

So to that you can write a DependencyInjection extension in your top level bundle that will do all of the validation. Not sure what should happen if something is invalid but you could something like this:

// 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);
        }
    }
}

haven't tested any of that but generally that is the base idea. You'll need to implement your config validation method.