How to Create Friendly Configuration for a Bundle

How to Create Friendly Configuration for a Bundle

If you open your main application configuration directory (usually config/packages/), you’ll see a number of different files, such as framework.yaml, twig.yaml and doctrine.yaml. Each of these configures a specific bundle, allowing you to define options at a high level and then let the bundle make all the low-level, complex changes based on your settings.

For example, the following configuration tells the FrameworkBundle to enable the form integration, which involves the definition of quite a few services as well as integration of other related components:

  • YAML

    1. framework:
    2. form: true
  • XML

    1. <?xml version="1.0" encoding="UTF-8" ?>
    2. <container xmlns="http://symfony.com/schema/dic/services"
    3. xmlns:framework="http://symfony.com/schema/dic/symfony"
    4. xsi:schemaLocation="http://symfony.com/schema/dic/services
    5. https://symfony.com/schema/dic/services/services-1.0.xsd
    6. http://symfony.com/schema/dic/symfony
    7. https://symfony.com/schema/dic/symfony/symfony-1.0.xsd">
    8. <framework:config>
    9. <framework:form/>
    10. </framework:config>
    11. </container>
  • PHP

    1. $container->loadFromExtension('framework', [
    2. 'form' => true,
    3. ]);

Using the Bundle Extension

Imagine you are creating a new bundle - AcmeSocialBundle - which provides integration with Twitter. To make your bundle configurable to the user, you can add some configuration that looks like this:

  • YAML

    1. # config/packages/acme_social.yaml
    2. acme_social:
    3. twitter:
    4. client_id: 123
    5. client_secret: your_secret
  • XML

    1. <!-- config/packages/acme_social.xml -->
    2. <?xml version="1.0" encoding="UTF-8" ?>
    3. <container xmlns="http://symfony.com/schema/dic/services"
    4. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    5. xmlns:acme-social="http://example.org/schema/dic/acme_social"
    6. xsi:schemaLocation="http://symfony.com/schema/dic/services
    7. https://symfony.com/schema/dic/services/services-1.0.xsd">
    8. <acme-social:config>
    9. <acme-social:twitter client-id="123" client-secret="your_secret"/>
    10. </acme-social:config>
    11. <!-- ... -->
    12. </container>
  • PHP

    1. // config/packages/acme_social.php
    2. $container->loadFromExtension('acme_social', [
    3. 'twitter' => [
    4. 'client_id' => 123,
    5. 'client_secret' => 'your_secret',
    6. ],
    7. ]);

The basic idea is that instead of having the user override individual parameters, you let the user configure just a few, specifically created, options. As the bundle developer, you then parse through that configuration and load correct services and parameters inside an “Extension” class.

Note

The root key of your bundle configuration (acme_social in the previous example) is automatically determined from your bundle name (it’s the snake case of the bundle name without the Bundle suffix ).

See also

Read more about the extension in How to Load Service Configuration inside a Bundle.

Tip

If a bundle provides an Extension class, then you should not generally override any service container parameters from that bundle. The idea is that if an Extension class is present, every setting that should be configurable should be present in the configuration made available by that class. In other words, the extension class defines all the public configuration settings for which backward compatibility will be maintained.

See also

For parameter handling within a dependency injection container see Using Parameters within a Dependency Injection Class.

Processing the $configs Array

First things first, you have to create an extension class as explained in How to Load Service Configuration inside a Bundle.

Whenever a user includes the acme_social key (which is the DI alias) in a configuration file, the configuration under it is added to an array of configurations and passed to the load() method of your extension (Symfony automatically converts XML and YAML to an array).

For the configuration example in the previous section, the array passed to your load() method will look like this:

  1. [
  2. [
  3. 'twitter' => [
  4. 'client_id' => 123,
  5. 'client_secret' => 'your_secret',
  6. ],
  7. ],
  8. ]

Notice that this is an array of arrays, not just a single flat array of the configuration values. This is intentional, as it allows Symfony to parse several configuration resources. For example, if acme_social appears in another configuration file - say config/packages/dev/acme_social.yaml - with different values beneath it, the incoming array might look like this:

  1. [
  2. // values from config/packages/acme_social.yaml
  3. [
  4. 'twitter' => [
  5. 'client_id' => 123,
  6. 'client_secret' => 'your_secret',
  7. ],
  8. ],
  9. // values from config/packages/dev/acme_social.yaml
  10. [
  11. 'twitter' => [
  12. 'client_id' => 456,
  13. ],
  14. ],
  15. ]

The order of the two arrays depends on which one is set first.

But don’t worry! Symfony’s Config component will help you merge these values, provide defaults and give the user validation errors on bad configuration. Here’s how it works. Create a Configuration class in the DependencyInjection directory and build a tree that defines the structure of your bundle’s configuration.

The Configuration class to handle the sample configuration looks like:

  1. // src/Acme/SocialBundle/DependencyInjection/Configuration.php
  2. namespace Acme\SocialBundle\DependencyInjection;
  3. use Symfony\Component\Config\Definition\Builder\TreeBuilder;
  4. use Symfony\Component\Config\Definition\ConfigurationInterface;
  5. class Configuration implements ConfigurationInterface
  6. {
  7. public function getConfigTreeBuilder()
  8. {
  9. $treeBuilder = new TreeBuilder('acme_social');
  10. $treeBuilder->getRootNode()
  11. ->children()
  12. ->arrayNode('twitter')
  13. ->children()
  14. ->integerNode('client_id')->end()
  15. ->scalarNode('client_secret')->end()
  16. ->end()
  17. ->end() // twitter
  18. ->end()
  19. ;
  20. return $treeBuilder;
  21. }
  22. }

Deprecated since version 4.2: Not passing the root node name to TreeBuilder was deprecated in Symfony 4.2.

See also

The Configuration class can be much more complicated than shown here, supporting “prototype” nodes, advanced validation, XML-specific normalization and advanced merging. You can read more about this in the Config component documentation. You can also see it in action by checking out some core Configuration classes, such as the one from the FrameworkBundle Configuration or the TwigBundle Configuration.

This class can now be used in your load() method to merge configurations and force validation (e.g. if an additional option was passed, an exception will be thrown):

  1. // src/Acme/SocialBundle/DependencyInjection/AcmeSocialExtension.php
  2. public function load(array $configs, ContainerBuilder $container)
  3. {
  4. $configuration = new Configuration();
  5. $config = $this->processConfiguration($configuration, $configs);
  6. // you now have these 2 config keys
  7. // $config['twitter']['client_id'] and $config['twitter']['client_secret']
  8. }

The processConfiguration() method uses the configuration tree you’ve defined in the Configuration class to validate, normalize and merge all the configuration arrays together.

Now, you can use the $config variable to modify a service provided by your bundle. For example, imagine your bundle has the following example config:

  1. <!-- src/Acme/SocialBundle/Resources/config/services.xml -->
  2. <?xml version="1.0" encoding="UTF-8" ?>
  3. <container xmlns="http://symfony.com/schema/dic/services"
  4. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  5. xsi:schemaLocation="http://symfony.com/schema/dic/services
  6. https://symfony.com/schema/dic/services/services-1.0.xsd">
  7. <services>
  8. <service id="acme.social.twitter_client" class="Acme\SocialBundle\TwitterClient">
  9. <argument></argument> <!-- will be filled in with client_id dynamically -->
  10. <argument></argument> <!-- will be filled in with client_secret dynamically -->
  11. </service>
  12. </services>
  13. </container>

In your extension, you can load this and dynamically set its arguments:

  1. // src/Acme/SocialBundle/DependencyInjection/AcmeSocialExtension.php
  2. // ...
  3. use Symfony\Component\Config\FileLocator;
  4. use Symfony\Component\DependencyInjection\Loader\XmlFileLoader;
  5. public function load(array $configs, ContainerBuilder $container)
  6. {
  7. $loader = new XmlFileLoader($container, new FileLocator(dirname(__DIR__).'/Resources/config'));
  8. $loader->load('services.xml');
  9. $configuration = new Configuration();
  10. $config = $this->processConfiguration($configuration, $configs);
  11. $definition = $container->getDefinition('acme.social.twitter_client');
  12. $definition->replaceArgument(0, $config['twitter']['client_id']);
  13. $definition->replaceArgument(1, $config['twitter']['client_secret']);
  14. }

Tip

Instead of calling processConfiguration() in your extension each time you provide some configuration options, you might want to use the Symfony\Component\HttpKernel\DependencyInjection\ConfigurableExtension to do this automatically for you:

  1. // src/Acme/HelloBundle/DependencyInjection/AcmeHelloExtension.php
  2. namespace Acme\HelloBundle\DependencyInjection;
  3. use Symfony\Component\DependencyInjection\ContainerBuilder;
  4. use Symfony\Component\HttpKernel\DependencyInjection\ConfigurableExtension;
  5. class AcmeHelloExtension extends ConfigurableExtension
  6. {
  7. // note that this method is called loadInternal and not load
  8. protected function loadInternal(array $mergedConfig, ContainerBuilder $container)
  9. {
  10. // ...
  11. }
  12. }

This class uses the getConfiguration() method to get the Configuration instance.

Processing the Configuration yourself

Using the Config component is fully optional. The load() method gets an array of configuration values. You can instead parse these arrays yourself (e.g. by overriding configurations and using [isset](https://www.php.net/manual/en/function.isset.php "isset") to check for the existence of a value). Be aware that it’ll be very hard to support XML:

  1. public function load(array $configs, ContainerBuilder $container)
  2. {
  3. $config = [];
  4. // let resources override the previous set value
  5. foreach ($configs as $subConfig) {
  6. $config = array_merge($config, $subConfig);
  7. }
  8. // ... now use the flat $config array
  9. }

Modifying the Configuration of Another Bundle

If you have multiple bundles that depend on each other, it may be useful to allow one Extension class to modify the configuration passed to another bundle’s Extension class. This can be achieved using a prepend extension. For more details, see How to Simplify Configuration of Multiple Bundles.

Dump the Configuration

The config:dump-reference command dumps the default configuration of a bundle in the console using the Yaml format.

As long as your bundle’s configuration is located in the standard location (YourBundle\DependencyInjection\Configuration) and does not have a constructor it will work automatically. If you have something different, your Extension class must override the [Extension::getConfiguration()](https://github.com/symfony/symfony/blob/4.4/src/Symfony/Component/DependencyInjection/Extension/Extension.php "Symfony\Component\DependencyInjection\Extension\Extension::getConfiguration()") method and return an instance of your Configuration.

Supporting XML

Symfony allows people to provide the configuration in three different formats: Yaml, XML and PHP. Both Yaml and PHP use the same syntax and are supported by default when using the Config component. Supporting XML requires you to do some more things. But when sharing your bundle with others, it is recommended that you follow these steps.

Make your Config Tree ready for XML

The Config component provides some methods by default to allow it to correctly process XML configuration. See “Normalization” of the component documentation. However, you can do some optional things as well, this will improve the experience of using XML configuration:

Choosing an XML Namespace

In XML, the XML namespace is used to determine which elements belong to the configuration of a specific bundle. The namespace is returned from the [Extension::getNamespace()](https://github.com/symfony/symfony/blob/4.4/src/Symfony/Component/DependencyInjection/Extension/Extension.php "Symfony\Component\DependencyInjection\Extension\Extension::getNamespace()") method. By convention, the namespace is a URL (it doesn’t have to be a valid URL nor does it need to exist). By default, the namespace for a bundle is http://example.org/schema/dic/DI_ALIAS, where DI_ALIAS is the DI alias of the extension. You might want to change this to a more professional URL:

  1. // src/Acme/HelloBundle/DependencyInjection/AcmeHelloExtension.php
  2. // ...
  3. class AcmeHelloExtension extends Extension
  4. {
  5. // ...
  6. public function getNamespace()
  7. {
  8. return 'http://acme_company.com/schema/dic/hello';
  9. }
  10. }

Providing an XML Schema

XML has a very useful feature called XML schema. This allows you to describe all possible elements and attributes and their values in an XML Schema Definition (an XSD file). This XSD file is used by IDEs for auto completion and it is used by the Config component to validate the elements.

In order to use the schema, the XML configuration file must provide an xsi:schemaLocation attribute pointing to the XSD file for a certain XML namespace. This location always starts with the XML namespace. This XML namespace is then replaced with the XSD validation base path returned from [Extension::getXsdValidationBasePath()](https://github.com/symfony/symfony/blob/4.4/src/Symfony/Component/DependencyInjection/Extension/ExtensionInterface.php "Symfony\Component\DependencyInjection\Extension\ExtensionInterface::getXsdValidationBasePath()") method. This namespace is then followed by the rest of the path from the base path to the file itself.

By convention, the XSD file lives in the Resources/config/schema/, but you can place it anywhere you like. You should return this path as the base path:

  1. // src/Acme/HelloBundle/DependencyInjection/AcmeHelloExtension.php
  2. // ...
  3. class AcmeHelloExtension extends Extension
  4. {
  5. // ...
  6. public function getXsdValidationBasePath()
  7. {
  8. return __DIR__.'/../Resources/config/schema';
  9. }
  10. }

Assuming the XSD file is called hello-1.0.xsd, the schema location will be https://acme_company.com/schema/dic/hello/hello-1.0.xsd:

  1. <!-- config/packages/acme_hello.xml -->
  2. <?xml version="1.0" encoding="UTF-8" ?>
  3. <container xmlns="http://symfony.com/schema/dic/services"
  4. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  5. xmlns:acme-hello="http://acme_company.com/schema/dic/hello"
  6. xsi:schemaLocation="http://symfony.com/schema/dic/services
  7. https://symfony.com/schema/dic/services/services-1.0.xsd
  8. http://acme_company.com/schema/dic/hello
  9. https://acme_company.com/schema/dic/hello/hello-1.0.xsd">
  10. <acme-hello:config>
  11. <!-- ... -->
  12. </acme-hello:config>
  13. <!-- ... -->
  14. </container>

This work, including the code samples, is licensed under a Creative Commons BY-SA 3.0 license.