触发事件后如何触发发布方法?

How I can fire publish method once the event is fired?

我有以下事件 class 定义:

use Symfony\Contracts\EventDispatcher\Event;

class CaseEvent extends Event
{
    public const NAME = 'case.event';

    // ...
}

我创建了一个订阅者如下:

use App\Event\CaseEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;

class CaseEventListener implements EventSubscriberInterface
{
    public static function getSubscribedEvents(): array
    {
        return [CaseEvent::NAME => 'publish'];
    }

    public function publish(CaseEvent $event): void
    {
        // do something
    }
}

我还在 services.yaml 定义了以下内容:

App\EventSubscriber\CaseEventListener:
  tags:
    - { name: kernel.event_listener, event: case.event}

为什么当我派发这样的事件时遵循监听器方法 publish() 永远不会执行?

/**
 * Added here for visibility but is initialized in the class constructor
 *
 * @var EventDispatcherInterface
 */
private $eventDispatcher;

$this->eventDispatcher->dispatch(new CaseEvent($args));

我怀疑问题出在 kernel.event_listener 但不确定如何正确订阅事件的侦听器。

更改您的订阅者,getSubscribedEvents() 如下所示:

public static function getSubscribedEvents(): array
{
    return [CaseEvent::class => 'publish'];
}

这利用了changes on 4.3;您不再需要指定事件名称,并使您使用的调度更简单(单独调度事件对象,并省略事件名称)。

您也可以按原样离开订阅者;并将调度调用更改为“旧样式”:

$this->eventDispatcher->dispatch(new CaseEvent($args), CaseEvent::NAME);

此外,从 services.yaml 中删除 event_listener 标签。由于您正在实施 EventSubscriberInterface,因此您不需要添加任何其他配置。