4 minute read

Add custom configuration to Symfony 4

Set configuration parameters without having a bundle.

Say you have a symfony 4 project and you are using the default code directory structure, being a /src directory in the root, where all your custom application code resides. Of course you have already read all about Setting up a Symfony 4 project.

Now say you want to add some application configuration; When using a bundle you would add configuration as beautifully described in the Symfony docs, but unfortunately you are not working in a bundle, so you will need a slightly different approach.

First of all, add an Extension and Configuration class as described in the docs above. After having done so, override the default getAlias method of the Symfony\Component\DependencyInjection\Extension\Extension, so you can add your own alias. This is not required, as the default alias is set to the namespaced classname of your extension class. For simplicity, we’ll set this alias to “app”.


     * @inheritdoc
     * @return string
    public function getAlias()
        return 'app';

     * @param array $configs
     * @param ContainerBuilder $container
     * @throws \Exception
    public function load(array $configs, ContainerBuilder $container)
        $configuration = new Configuration();
        $config = $this->processConfiguration($configuration, $configs);
        foreach($config as $key => $value) {
            $container->setParameter($this->getAlias() . '.' . $key  , $value);

An extension also needs a load method, which will parse the configuration and stores it in the container ( or does something else with it ).

Now you can add a yaml file with your config. “app” is the alias you have set in your extension.

            ears: long
            hair: short
            ears: flat
            hair: long

And you will need to let the application know it has to load and process this file.


     * @param ContainerBuilder $container
     * @param LoaderInterface $loader
     * @throws \Exception
    protected function configureContainer(ContainerBuilder $container, LoaderInterface $loader)
        // Register your newly created extension
        $container->registerExtension(new Extension());

        // Existing code.

        // Load own configuration files.
        $loader->load($confDir .'/app_config.yaml');

And that’s it. Your configuration will be read and can be fetched as parameters from the container.


Want to find out what we can do for you?