相关疑难解决方法(0)

在Symfony2中,为什么注入服务容器而不是单个服务是个坏主意?

我找不到这个答案......

如果我注入服务容器,如:

// config.yml
my_listener:
   class: MyListener
   arguments: [@service_container]

my_service:
   class: MyService

// MyListener.php
class MyListener
{
    protected $container;

    public function __construct(ContainerInterface $container)
    {
        $this->container = $container;
    }

    public function myFunction()
    {
        $my_service = $this->container->get('my_service');
        $my_service->doSomething();
    }
}
Run Code Online (Sandbox Code Playgroud)

然后它的工作方式和我做的一样:

// config.yml
my_listener:
   class: MyListener
   arguments: [@my_service]

my_service:
   class: MyService

// MyListener.php    
class MyListener
{
    protected $my_service;

    public function __construct(MyService $my_service)
    {
        $this->my_service = $my_service;
    }

    public function myFunction()
    {
        $this->my_service->doSomething();
    }
}
Run Code Online (Sandbox Code Playgroud)

那么为什么我不应该只注入服务容器,并从我的类中获取服务?

dependency-injection symfony

21
推荐指数
3
解决办法
5576
查看次数

标签 统计

dependency-injection ×1

symfony ×1