我找不到这个答案......
如果我注入服务容器,如:
// 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)
那么为什么我不应该只注入服务容器,并从我的类中获取服务?