Pierre de LESPINAY
Pierre de LESPINAY

Reputation: 46178

Symfony 2 - Service dynamic imports

I have parameters defined as:

parameters:
    config1:
        title: Title 1
        data_proc: getDataOne
        options: [things, stuff]
    config2:
        title: Title 2
        data_proc: getDataTwo
        options: [things, stuff]
#...

A service defined as

my_service:
    class: Me\MyBundle\Services\MyService
    arguments:
        - @security.context
        - @doctrine.dbal.my_connection
        - %config% # the parameter that I'd like to be dynamic

controllers like

class ProduitController extends Controller
{
    public function list1Action()
    {
        $ssrs = $this->get('my_service'); // with config1 params
        # ...
    }
    public function list2Action()
    {
        $ssrs = $this->get('my_service'); // with config2 params
        # ...
    }
    #...
}

Several controllers using my_service.
My list1Action() should call my_service by injecting only config1 parameters

How can I do that without having to define as many services as controllers ?

Upvotes: 3

Views: 957

Answers (2)

Vitalii Zurian
Vitalii Zurian

Reputation: 17976

In your Me\MyBundle\Services\MyService you could define public method, which will set new parameters (setParameters($parameters) for example). Then in your controller you could do this:

class ProduitController extends Controller
{
    public function list1Action()
    {
        $config = $this->container->getParameter('config1');
        $ssrs = $this->get('my_service')->setParameters($config);
    }

    public function list2Action()
    {
        $config = $this->container->getParameter('config2');
        $ssrs = $this->get('my_service')->setParameters($config);
    }
}

This would be an optimal solution.

Of course, you could override some core Classes and achieve automatic injection with number part incremented, but is it really worth of the time it might cost?

Upvotes: 1

Carlos Granados
Carlos Granados

Reputation: 11351

Define two services with different arguments but the same class and get one or the other

Upvotes: 2

Related Questions