调度员不调度我的事件 symfony [英] dispatcher doesn't dispatch my event symfony
问题描述
我有一个 ExampleListener 类,如下所示:
I have an ExampleListener class that look like :
<?php
namespace AppBundle\EventListener;
class ExampleListener
{
public function helloWorld()
{
echo "Hello World!";
}
}
这是我的 services.yml
This is my services.yml
services:
my.event:
class: AppBundle\EventListener\ExampleListener
tags:
- { name: kernel.event_listener, event: my.event, method: helloWorld }
然后从控制器我试图调度事件.
And then from controller i'm trying to dispatch the event.
$dispatcher = new EventDispatcher();
$dispatcher->dispatch('my.event')
我没有任何错误,但从未调用 helloWorld 函数.我的活动结束了:
I don't have any error but the helloWorld function is never called. My event is up :
php bin/console debug:event-dispatcher my.event
php bin/console debug:event-dispatcher my.event
结果是:
#1 AppBundle\EventListener\ExampleListener::helloWorld() 0
为什么调度员没有正确调用事件?谢谢.
Why dispatcher doens't call the event right? Thanks.
推荐答案
您创建了一个新的事件调度程序,这与 Symfony 用于注册您在容器配置中定义的事件侦听器不同.
You have created a new event dispatcher, which is not the same as Symfony uses to register event listeners you define in you container configuration.
不要自己创建事件调度程序,而是使用 Symfony 已经定义的事件调度程序.您可以从容器中获取它,例如在控制器中:
Instead of creating the event dispatcher yourself, use the one that's already defined by Symfony. You can fetch it from the container, for example in a controller:
$this->container->get('event_dispatcher')->dispatch('my.event');
如果您需要从服务调度事件,只需将 event_dispatcher
服务作为构造函数参数之一传递:
If you need to dispatch your event from a service, simply pass the event_dispatcher
service as one of constructor arguments:
services:
my_service:
class: Foo\MyService
arguments:
- @event_dispatcher
这篇关于调度员不调度我的事件 symfony的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!