简体   繁体   中英

Symfony2 - Configuration - inject root node parameter to get the whole configuration

I wonder why it is not possible to inject the root node configuration namespace into a service.

Example configuration:

my_bundle: 
   foo: bar
   foobar: 123
   bar: 1

This would be the service configuration in MyBundle/Resources/config/services.xml.

...
<service id="my_bundle.service.my" class="MyService">
   <argument>%my_bundle%</argument>
</service>
...

Now I would like to inject the configuration into my service class. But this is not working because symfony2 does not know anything about the configuration root node "my_bundle".

class MyService
{
     public function __construct($config) {}
}

I know that I can split the config and add as many constructor arguments as I need in the service class to make it work. But this would lead to an huge amount of arguments in the constructor.

Further I think that injection of the whole symfony2 container is bad practise.

Maybe one of you can answer me: 1. Why this can not work? 2. Do I understand the entire configuration system wrong? 3. I thought that all what was defined under the namespace "my_bundle" is available if I inject the root node?

Or maybe anyone of you found a solution for this and share it?

Thanks.

In you bundle extension, create a parameter:

public function load(array $configs, ContainerBuilder $container)
{
    $configuration = new Configuration();
    $config = $this->processConfiguration($configuration, $configs);

    $container->setParameter('my_bundle', $config);
}

Then you can inject it in your service declaration

Explanations

What you are creating by adding options under the my_bundle key is a bundle configuration, which is processed in your bundle extension.

It's not a parameter defined under the parameter keyword, but in your bundle extension, you have access to the container, so in that place you can add this bundle configuration as a parameter (once processed, checked etc), and then inject it in your service arguments.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM