Symfony5 监听捆绑包中的自定义事件

Symfony5 Listen custom event in bundle

全部

我想收听自定义包中的事件。我知道问题出在连接事件上,因为当我在主路径中使用它时它起作用了。我的代码很简单:

首先我有一个像 BeforeCrudActionEvent 这样的事件 class,它有一些默认值 felds/methods。 其次,我创建了我的事件实例 class 并使用 EventDispatcherInterface 像这样调度它:

$event = new BeforeCrudActionEvent();
$this->get('event_dispatcher')->dispatch($event);

事件名称未定义,自动生成(由class的命名空间和名称组成)。

最后我创建了实现 EventSubscriberInterface

的订阅者 class
class TestSubscriber implements EventSubscriberInterface
{

    public static function getSubscribedEvents()
    {
        return [
            BeforeCrudActionEvent::class => ['updateList']
        ];
    }

    public function updateList(BeforeCrudActionEvent $event)
    {
        throw new \Exception("It's works");
    }
}

正如我之前所写,当订阅者 class 在主目录中时它可以工作,但是当它在自定义包中时它不会。我确定它必须添加到 service.yaml 文件,但我在文档中找不到此配置。我应该使用哪个标签和哪个事件(如果需要)?

doc段落的末尾写:

You can also manually add the kernel.event_subscriber tag.

因此您需要注册您的 eventSubscriber 有一个服务并添加标签“kernel.event_subscriber”。

NameSpace\TestSubscriber:
    tags:
        - { name: kernel.event_subscriber }

之后,您可以检查您的订阅者是否配置了对 php bin/console debug:event-dispatcher "event.name"

的调用