Passing dynamic variables to a service constructor

symfony

Solution

If, for whatever reason, you are unable to configure the service after instantiation (i.e., with a configurator). What about delegating that responsibility to a factory? It will let you instantiate services with "dynamic arguments".

services:
    MyCustomServiceFactory:
        class: MyClassFactory
        arguments: [ @dynamicService, %time_prefix% ]
    MyCustomService:
        class:              MyClass
        factory_service:    MyCustomServiceFactory
        factory_method:     get

Your factory would like something like this:

class MyClassFactory
{
    private $dynamicService;
    private $timePrefix;

    public function __construct(MyDynamicService $dynamicService, $timePrefix)
    {
        $this->dynamicService = $dynamicService;
        $this->timePrefix = $timePrefix;

    }

    public function get()
    {
        // Dynamic arguments based on application logic.
        $dynamicArg1 = $this->dynamicService->getArg()
        $dynamicArg2 = $this->timePrefix . time();

        return new MyClass($dynamicArg1, $dynamicArg2);
    }
}

Problem

I have a service in Symfony2 that looks like: ``` services: MyCustomService: class: MyClass arguments: //Arguments aren't static, but dynamic based on application logic. ``` Is it possible to pass dynamic variables to a service's constructor? There doesn't seem to be any extra parameters within a controller's `$this->get('MyCustomService');` Is there something I'm missing?

Original source