3

我的参数定义为:

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

服务定义为

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

控制器喜欢

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
        # ...
    }
    #...
}

几个控制器使用my_service.
list1Action()应该my_service通过只注入config1参数来调用

我怎样才能做到这一点而不必定义与控制器一样多的服务?

4

2 回答 2

2

定义具有不同参数但具有相同类的两个服务并获取一个或另一个

于 2012-08-28T16:09:38.147 回答
1

在你的Me\MyBundle\Services\MyService你可以定义公共方法,它将设置新的参数(setParameters($parameters)例如)。然后在你的控制器中你可以这样做:

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);
    }
}

这将是一个最佳解决方案。

当然,你可以重写一些核心类并实现自动注入,增加数字部分,但这真的值得花时间吗?

于 2012-08-29T08:00:31.080 回答