symfony2

Configuration for own bundles

Introduction#

This is a description how you can create configuration for you own bundle in the /app/config/config.{yml,xml}

Create configuration in the app/config/config.yml

amazingservice:
    url: 'https://amazing.com'
    client_id: 'test_client_1'
    client_secret: 'test_secret'

This is a basic example for create configuration in yml format, for following the yml format you can take deeper configuration.

Set the config in the created bundle

For instance you have a bundle, which generated by the symfony console. In this case in the DependencyInjection/Configuration.php you have to insert your configuration representation:

$treeBuilder = new TreeBuilder();
        $rootNode = $treeBuilder->root('amazingservice');

        $rootNode->children()
            ->scalarNode('url')->end()
            ->scalarNode('client_id')->end()
            ->scalarNode('client_secret')->end()
            ->end()
        ->end();

Basically in the DependencyInjection/AmazingserviceExtension.php you will see the following lines:

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

It is not enough for getting the configuration in the Srevices. You have to take it into the container.

$container->setParameter(
  'amazingservice.config',
  $config
);

In this case the config in the container, so if your Service getting the container as a constructor parameter:

base.amazingservice:
        class: Base\AmazingBundle\Services\AmazingServices
        arguments: [@service_container]

Then you can get the configuration in the service with the following code, where the configuration will be an associative array:

private $config;

public function __construct(Container $container){
  $this->config = $container->getParameter('amazingservice.config');   
}

This modified text is an extract of the original Stack Overflow Documentation created by the contributors and released under CC BY-SA 3.0 This website is not affiliated with Stack Overflow