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
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"))']
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With