Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to extend config of different bundle in Symfony2?

Tags:

php

symfony

I know I can overwrite templates or extend classes of other bundles. But can I extend also configs? I was hoping to be able to load other namespaces from config in DependenyInjection/AcmeExtension.php's load method, but I haven't found anything about it anywhere.

Example:

I have AcmeBundle which defines following in config:

acme:
    a: 1

I want to extend this bundle (in new bundle called AwesomeAcmeBundle) and be able to define another variables either by adding them to original namespace:

acme:
    a: 1
    b: 2

or by wrapping original namespace to new one and adding new variables there:

awesome_acme:
    a: 1
    b: 2
like image 466
Ondrej Slinták Avatar asked Oct 13 '11 13:10

Ondrej Slinták


1 Answers

I had similar needs and I have solved them in the following way:

1) Extend the parent's Configuration class

//FooBundle\DependencyInjection\Configuration.php

use DerpBundle\DependencyInjection\Configuration as BaseConfiguration;

class Configuration extends BaseConfiguration
{

    public function getConfigTreeBuilder()
    {
        $treeBuilder = parent::getConfigTreeBuilder();

        //protected attribute access workaround
        $reflectedClass = new \ReflectionObject($treeBuilder);
        $property = $reflectedClass->getProperty("root");
        $property->setAccessible(true);

        $rootNode = $property->getValue($treeBuilder);

        $rootNode
           ->children()
           ...

        return $treeBuilder;
     }
}

2) Create own extension that actually can handle the new configuration entries

class FooExtension extends Extension
{

    public function load(array $configs, ContainerBuilder $container)
    {

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

        //custom parameters
        $container->setParameter('new_param_container_name', $config['new_param_name']);

     ...
     }
}

3) in the app\config\config.yml you can use in your new foo attribute-set all the parameters that derp (as a parent bundle) has plus any of your new params that you have defined in the Configuration.php.

like image 85
axasanya Avatar answered Sep 30 '22 09:09

axasanya