【发布时间】:2014-05-29 10:34:15
【问题描述】:
我找不到这个问题的答案...
如果我注入服务容器,比如:
// 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();
}
}
然后它就像我一样工作:
// 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();
}
}
那么为什么我不应该只注入服务容器,并从我的类中获取服务呢?
【问题讨论】:
标签: symfony dependency-injection