Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamic service id in an argument in symfony2?

Tags:

config

symfony

Is it possible to set the service id in an argument dynamically (e.g. like a class name which could be set via parameter) in Symfony 2 (xml configs)?

The following does not work

<service id="myservice" class="myservice.php">
    <argument type="service" id="%dynamic_service_name%" />
</service>

<service id="service1" class="foobar\service1" />
<service id="service2" class="foobar\service1" />

the idea is to set the param %dynamic_service_name% dynamically to "service1" or "service2", so the needed instance/object is passed to myservice-class, e.g. in the Extension::load() via $container->setParameter('dynamic_service_name','service1');

Thanks a lot

like image 335
user1826848 Avatar asked Mar 25 '13 12:03

user1826848


2 Answers

You can read a parameter into your service definition, with the parameter() function, and create a service with the service() function. So you can create a dynamic service

In your parameters.yml

  parameters:
      dynamic_service_name:  mydynamicservice

In your services.yml

  myservice:
        class: My\Service
        arguments:['@=service(parameter("dynamic_service_name"))']
like image 196
Arno Avatar answered Oct 19 '22 23:10

Arno


You can use CompilerPass:

class DynamicServiceCompilerPass implements CompilerPassInterface
{
    public function process(ContainerBuilder $container)
    {
        $container->getDefinition('myservice')
            ->setArguments(array(new Reference($container->getParameter('dynamic_service_name'))));
    }
}

and add it to your Bundle class:

public function build(ContainerBuilder $container)
{
    parent::build($container);

    $container->addCompilerPass(new DynamicServiceCompilerPass());
}

FOLLOW UP:

Since Symfony 2.4 you can use Expression Language like this:

<services>
    <service id="myservice" class="My\Service">
        <argument type="expression">service(container.hasParameter('dynamic_service_name') ? parameter('dynamic_service_name') : 'default_service_name')</argument>
    </service>
</services>
like image 16
Furgas Avatar answered Oct 20 '22 01:10

Furgas