假设我有一个侦听器作为这样的服务
class MyListener
{
/**
* @var Symfony\Component\EventDispatcher\ContainerAwareEventDispatcher
*/
private $dispatcher;
function __construct(ContainerAwareEventDispatcher $dispatcher)
{
$this->dispatcher = $dispatcher;
}
public function onKernelRequest(GetResponseEvent $event)
{
//in my logic here I use $this->dispatcher->dispatch(my-own-event)
}
}
service.yml
ap.my_listener:
class: my-name-space\MyListener
tags:
- { name: kernel.event_listener, event: kernel.request, method: onKernelRequest }
arguments: ["@debug.event_dispatcher.inner"]
在开发环境中工作正常,但是在清除缓存后切换到生产环境时,出现此异常:
The service "ap.my_listener" has a dependency on a non-existent service "debug.event_dispatcher.inner"
按时间,我只是注入了所有容器,所以到底发生了什么,还有另一种方法可以注入Event Dispatcher,而无需从容器中获取它
答案 0 :(得分:1)
您应该只注入事件分配器,并使用类似的接口
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
class MyListener
{
/**
* @var Symfony\Component\EventDispatcher\EventDispatcherInterface
*/
private $dispatcher;
function __construct(EventDispatcherInterface $dispatcher)
{
$this->dispatcher = $dispatcher;
}
public function onKernelRequest(GetResponseEvent $event)
{
//in my logic here I use $this->dispatcher->dispatch(my-own-event)
}
}
//service.yml
ap.my_listener:
class: my-name-space\MyListener
tags:
- { name: kernel.event_listener, event: kernel.request, method: onKernelRequest }
arguments: ["@event_dispatcher"]