Skip to content

How to Create Friendly Configuration for a Bundle

Edit this page

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 the integration of other related components:

1
2
3
# config/packages/framework.yaml
framework:
    form: true

There are two different ways of creating friendly configuration for a bundle:

  1. Using the main bundle class: this is recommended for new bundles and for bundles following the recommended directory structure;
  2. Using the Bundle extension class: this was the traditional way of doing it, but nowadays it's only recommended for bundles following the legacy directory structure.

Using the AbstractBundle Class

In bundles extending the AbstractBundle class, you can add all the logic related to processing the configuration in that class:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
// src/AcmeSocialBundle.php
namespace Acme\SocialBundle;

use Symfony\Component\Config\Definition\Configurator\DefinitionConfigurator;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
use Symfony\Component\HttpKernel\Bundle\AbstractBundle;

class AcmeSocialBundle extends AbstractBundle
{
    public function configure(DefinitionConfigurator $definition): void
    {
        $definition->rootNode()
            ->children()
                ->arrayNode('twitter')
                    ->children()
                        ->integerNode('client_id')->end()
                        ->scalarNode('client_secret')->end()
                    ->end()
                ->end() // twitter
            ->end()
        ;
    }

    public function loadExtension(array $config, ContainerConfigurator $container, ContainerBuilder $builder): void
    {
        // the "$config" variable is already merged and processed so you can
        // use it directly to configure the service container (when defining an
        // extension class, you also have to do this merging and processing)
        $container->services()
            ->get('acme_social.twitter_client')
            ->arg(0, $config['twitter']['client_id'])
            ->arg(1, $config['twitter']['client_secret'])
        ;
    }
}

Read how to define configuration values to learn about all the node types and options available when defining the configuration tree.

Note

The configure() and loadExtension() methods are called only at compile time.

Tip

The AbstractBundle::configure() method also allows importing the configuration definition from one or more files:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// src/AcmeSocialBundle.php
namespace Acme\SocialBundle;

// ...
class AcmeSocialBundle extends AbstractBundle
{
    public function configure(DefinitionConfigurator $definition): void
    {
        $definition->import('../config/definition.php');
        // you can also use glob patterns
        //$definition->import('../config/definition/*.php');
    }

    // ...
}
1
2
3
4
5
6
7
8
9
10
// config/definition.php
use Symfony\Component\Config\Definition\Configurator\DefinitionConfigurator;

return static function (DefinitionConfigurator $definition): void {
    $definition->rootNode()
        ->children()
            ->scalarNode('foo')->defaultValue('bar')->end()
        ->end()
    ;
};

Using the Bundle Extension

This is the traditional way of creating friendly configuration for bundles. For new bundles it's recommended to use the main bundle class, but the traditional way of creating an extension class still works.

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

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

The basic idea is that instead of having the user override individual parameters, you let the user configure only a few, specifically created, options. As the bundle developer, you then parse through that configuration and load the 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.

Processing the $configs Array

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 the configuration 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
4
5
6
7
8
[
    [
        'twitter' => [
            'client_id' => 123,
            'client_secret' => 'your_secret',
        ],
    ],
]

Notice that this is an array of arrays, not 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 under it, the incoming array might look like this:

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

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

Symfony's Config component helps 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 this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
// src/DependencyInjection/Configuration.php
namespace Acme\SocialBundle\DependencyInjection;

use Symfony\Component\Config\Definition\Builder\TreeBuilder;
use Symfony\Component\Config\Definition\ConfigurationInterface;

class Configuration implements ConfigurationInterface
{
    public function getConfigTreeBuilder(): TreeBuilder
    {
        $treeBuilder = new TreeBuilder('acme_social');

        $treeBuilder->getRootNode()
            ->children()
                ->arrayNode('twitter')
                    ->children()
                        ->integerNode('client_id')->end()
                        ->scalarNode('client_secret')->end()
                    ->end()
                ->end() // twitter
            ->end()
        ;

        return $treeBuilder;
    }
}

Warning

Build the configuration tree from static information only. Don't read container parameters (such as kernel.debug), environment variables or the state of the machine (installed PHP extensions, operating system) while building it: Symfony generates the configuration reference from the tree, so it must be identical in every environment. When a default value depends on such things, leave the node without a default, describe the fallback in info() and resolve it when loading the configuration.

See also

The Configuration class can be much more complicated than shown here, supporting "prototype" nodes, advanced validation, plural/singular 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
2
3
4
5
6
7
8
9
10
// src/DependencyInjection/AcmeSocialExtension.php
public function load(array $configs, ContainerBuilder $container): void
{
    $configuration = new Configuration();

    $config = $this->processConfiguration($configuration, $configs);

    // you now have these 2 config keys
    // $config['twitter']['client_id'] and $config['twitter']['client_secret']
}

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
2
3
4
5
6
7
8
9
10
// src/Resources/config/services.php
namespace Symfony\Component\DependencyInjection\Loader\Configurator;

use Acme\SocialBundle\TwitterClient;

return function (ContainerConfigurator $container) {
    $container->services()
        ->set('acme_social.twitter_client', TwitterClient::class)
            ->args([abstract_arg('client_id'), abstract_arg('client_secret')]);
};

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
// src/DependencyInjection/AcmeSocialExtension.php
namespace Acme\SocialBundle\DependencyInjection;

use Symfony\Component\Config\FileLocator;
use Symfony\Component\DependencyInjection\Loader\PhpFileLoader;

public function load(array $configs, ContainerBuilder $container): void
{
    $loader = new PhpFileLoader($container, new FileLocator(dirname(__DIR__).'/Resources/config'));
    $loader->load('services.php');

    $configuration = new Configuration();
    $config = $this->processConfiguration($configuration, $configs);

    $definition = $container->getDefinition('acme_social.twitter_client');
    $definition->replaceArgument(0, $config['twitter']['client_id']);
    $definition->replaceArgument(1, $config['twitter']['client_secret']);
}

Tip

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
// src/DependencyInjection/HelloExtension.php
namespace Acme\HelloBundle\DependencyInjection;

use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\HttpKernel\DependencyInjection\ConfigurableExtension;

class AcmeHelloExtension extends ConfigurableExtension
{
    // note that this method is called loadInternal and not load
    protected function loadInternal(array $mergedConfig, ContainerBuilder $container): void
    {
        // ...
    }
}

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

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 to check for the existence of a value):

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

    // ... now use the flat $config array
}

Using Container Parameters as Default Values

Sometimes the default value of an option depends on a container parameter. For example, a logging option that is enabled only when the application runs in debug mode:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// inside the Configuration class
$treeBuilder->getRootNode()
    ->children()
        ->booleanNode('logging')->defaultValue('%kernel.debug%')->end()
    ->end()
;

// inside the extension class
$config = $this->processConfiguration($configuration, $configs);

// when users don't set the option, this is the '%kernel.debug%' string,
// which PHP always considers true
if ($config['logging']) {
    // ...
}

Symfony resolves the parameters that users write in their configuration files (e.g. logging: '%kernel.debug%') before passing them to the extension. However, the Config component knows nothing about container parameters, so it returns the default value as the %kernel.debug% string. This works when you only pass the value to a service argument or to another parameter, because the container resolves it later. It doesn't work when the extension needs the real value.

In that case, define the option without a default value, describe the fallback with info() and resolve it when loading the configuration:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
// inside the Configuration class
$treeBuilder->getRootNode()
    ->children()
        ->booleanNode('logging')
            ->info('Defaults to the value of the "kernel.debug" parameter')
        ->end()
    ->end()
;

// inside the extension class (in bundles extending AbstractBundle, do this
// in loadExtension() using its $config and $builder arguments)
$config = $this->processConfiguration($configuration, $configs);

// the processed config doesn't contain the option when users don't set it
$isLoggingEnabled = $config['logging']
    ?? $container->getParameter('kernel.debug');

Modifying the Configuration of Another Bundle

When building reusable and extensible applications, developers often have to choose between creating a single large bundle or multiple smaller bundles. A single bundle doesn't allow users to remove the features they don't use. Multiple bundles make configuration repetitive, because users must define the same settings in several bundles.

To avoid this, a bundle can prepend settings to the configuration of any other bundle, as if the user had written them in the application configuration. For example, you can use this to configure the entity manager name used by multiple bundles or to enable an optional feature that depends on another bundle being loaded as well.

Since these settings are prepended, the settings defined explicitly in the config/* files override them. If more than one bundle prepends the same option of the same extension, the bundle that is registered first takes priority: bundles registered later won't override that option.

Prepending Configuration in the Bundle Class

In bundles extending the AbstractBundle class, define the prependExtension() method:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
// src/AcmeHelloBundle.php
namespace Acme\HelloBundle;

use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
use Symfony\Component\HttpKernel\Bundle\AbstractBundle;

class AcmeHelloBundle extends AbstractBundle
{
    public function prependExtension(ContainerConfigurator $container, ContainerBuilder $builder): void
    {
        // prepend some config options
        $builder->prependExtensionConfig('framework', [
            'cache' => ['prefix_seed' => 'acme/hello'],
        ]);

        // prepend the config defined in a file
        $container->import('../config/packages/cache.php');
    }
}

Note

The prependExtension() method is called only at compile time.

Alternatively, pass true as the third argument of the extension() method to prepend the given configuration instead of appending it:

1
2
3
4
5
6
7
8
public function prependExtension(ContainerConfigurator $container, ContainerBuilder $builder): void
{
    // ...

    $container->extension('framework', [
        'cache' => ['prefix_seed' => 'acme/hello'],
    ], true);
}

Prepending Configuration in the Extension Class

In bundles that define an extension class, make that class implement PrependExtensionInterface:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
// src/DependencyInjection/AcmeHelloExtension.php
namespace Acme\HelloBundle\DependencyInjection;

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

class AcmeHelloExtension extends Extension implements PrependExtensionInterface
{
    // ...

    public function prepend(ContainerBuilder $container): void
    {
        // ...
    }
}

8.1

In Symfony versions prior to 8.1, the Extension class was in Symfony\Component\HttpKernel\DependencyInjection\Extension. It was deprecated in Symfony 8.1 and replaced by Symfony\Component\DependencyInjection\Extension\Extension.

Symfony calls the prepend() method of all extensions before calling the load() method of any of them. Inside it, you have full access to the ContainerBuilder instance and you can call its prependExtensionConfig() method to prepend settings to any extension.

The following example prepends a setting to the configuration of several bundles and disables an option in them when another bundle is not registered:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
// src/DependencyInjection/AcmeHelloExtension.php
public function prepend(ContainerBuilder $container): void
{
    $bundles = $container->getParameter('kernel.bundles');
    if (!isset($bundles['AcmeGoodbyeBundle'])) {
        // AcmeGoodbyeBundle is not registered, so set "use_acme_goodbye"
        // to false in the config of "acme_something" and "acme_other";
        // if the user sets it to true in their config/packages/ files,
        // the final value will be true
        foreach (['acme_something', 'acme_other'] as $name) {
            if ($container->hasExtension($name)) {
                $container->prependExtensionConfig($name, [
                    'use_acme_goodbye' => false,
                ]);
            }
        }
    }

    // get the configuration of AcmeHelloExtension (it's a list of configuration)
    $configs = $container->getExtensionConfig($this->getAlias());

    // iterate in reverse to preserve the original order after prepending the config
    foreach (array_reverse($configs) as $config) {
        // check if entity_manager_name is set in the "acme_hello" configuration
        if (isset($config['entity_manager_name'])) {
            // prepend the acme_something settings with the entity_manager_name
            $container->prependExtensionConfig('acme_something', [
                'entity_manager_name' => $config['entity_manager_name'],
            ]);
        }
    }
}

If AcmeGoodbyeBundle is not registered and the entity_manager_name option of acme_hello is set to non_default, this is the equivalent of writing the following configuration:

1
2
3
4
5
6
7
# config/packages/acme_something.yaml
acme_something:
    use_acme_goodbye: false
    entity_manager_name: non_default

acme_other:
    use_acme_goodbye: false

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>/src/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() method and return an instance of your Configuration.

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