首页 >后端开发 >php教程 >使用简单的 Trait 自动化 Symfony\\Component\\EventDispatcher\\EventSubscriberInterface::getSubscribedEvents()

使用简单的 Trait 自动化 Symfony\\Component\\EventDispatcher\\EventSubscriberInterface::getSubscribedEvents()

Patricia Arquette
Patricia Arquette原创
2024-11-27 18:10:11412浏览

Automate Symfony\Component\EventDispatcher\EventSubscriberInterface::getSubscribedEvents() with simple Trait

你喜欢SymfonyComponentEventDispatcherEventSubscriberInterface及其getSubscribedEvents()方法吗?

class AwesomeSubscriber implements Symfony\Component\EventDispatcher\EventSubscriberInterface
{

    public static function getSubscribedEvents(): array
    {
        return [
            HappyEvent::class => 'happy',
            CoolEvent::class => 'coll',
        ];
    }

    public function happy(HappyEvent $event): void {}

    public function coll(CoolEvent $event): void {}

}

我讨厌它!

  1. 具有文本方法名称表示的数组
  2. 事件类名被多次写入?

是的,新的 Symfony 有属性 #[AsEventListener],但是如果你使用其他框架或旧版本的事件调度程序或者你不喜欢属性怎么办?

有简单的解决方案吗?
请参阅此特征 https://github.com/Zarganwar/symfony-event-dispatcher-utils。
这为您提供了一种简单(自动)的方式来订阅 __invoke 方法的事件。

class AwesomeSubscriber implements Symfony\Component\EventDispatcher\EventSubscriberInterface
{
    use AutoEventSubscriberTrait; // <<<--- This is it! ❤️

    public function __invoke(HappyEvent|AnotherEvent $event): void {}

}

SRP 每个活动的订阅者

class HappySubscriber implements Symfony\Component\EventDispatcher\EventSubscriberInterface
{
    use AutoEventSubscriberTrait;

    public function __invoke(HappyEvent $event): void {}

}

class CoolSubscriber implements Symfony\Component\EventDispatcher\EventSubscriberInterface
{
    use AutoEventSubscriberTrait;

    public function __invoke(CoolEvent $event): void {}

}

当然,您可以使用接口和联合类型。

前往 https://github.com/Zarganwar/symfony-event-dispatcher-utils 并安装

作曲家需要 zarganwar/symfony-event-dispatcher-utils

享受吧! ?

以上是使用简单的 Trait 自动化 Symfony\\Component\\EventDispatcher\\EventSubscriberInterface::getSubscribedEvents()的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn