A parameters.yml per bundle, symfony2

2019-02-09 07:57发布

问题:

I was wondering if it's possible to defined a parameters.yml file for every bundle or only for the bundles that need it and load those.

I have searched a lot but i can't find such solution.

回答1:

You should clarify a bit; you want every single bundles to automatically include a parameters.yml file? I am afraid you would need to modify Symfony's DI core. There is an easy alternative though.

If you create your own bundle with some DependencyInjection then you can add $loader->load('parameters.yml'); in the bundle's extension class.

The extension class should be located in YourBundle/DependencyInjection/YourBundleExtension.php.

The class should look like the following

class YourBundleExtension extends Extension
{
    /**
     * {@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');
        $loader->load('parameters.yml'); // Adding the parameters file
    }
}

So in this case the parameters.yml file would be in YourBundle/Resources/config/parameters.yml.



回答2:

If you just want to include a parameters file from a bundle into your configuration, just follow the normal format for importing extra configuration files from bundles (the default app shows how to do this with routing). Update your config to include your parameters file like this:

imports:
    - { resource: parameters.yml }
    - { resource: @YourBundle/Resources/config/parameters.yml }
    - { resource: security.yml }
    - ...

Your parameters file should follow the same format as the default one:

parameters:
    my.parameter: "my value"