0

假设我有一个听众作为这样的服务

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

服务.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 而无需从容器中检索它

4

1 回答 1

2

您应该只注入事件调度程序并使用类似的接口

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"]
于 2019-12-12T22:35:56.650 回答