使用Cutom事件代替Symfony中的依赖项注入有好处吗?

问题描述 投票:1回答:1

我有一个Mailer服务,该服务负责创建和发送电子邮件。我也有Registration服务来确认用户注册。

[发送自定义事件,订阅它,然后使用Mailer服务发送电子邮件,而不是仅通过注入Mailer中的Registration服务,这有什么好处?

我有点困惑。第一个似乎很难维护,但是我看了太多次了,也许我应该考虑一下。

换句话说。我应该这样做:

class Registration
{
    public function __construct(EventDispatcherInterface $eventDispatcher)
    {
        $this->eventDispatcher = $eventDispatcher;
    }

    public function confirm()
    {
        // ...

        $this->eventDispatcher->dispatch('myApp.registration.confirmed', new MyCustomEvent());
    }
}

class RegistrationSubscriber implements EventSubscriberInterface
{
    public function __construct(Mailer $mailer)
    {
        $this->mailer = $mailer;
    }

    // ...

    public function onRegistrationConfirmed(MyCustomEvent $event)
    {
        // ...

        $this->mailer->sendRegistrationConfirmedEmail();
    }
}

或此:

class Registration
{
    public function __construct(Mailer $mailer)
    {
        $this->mailer = $mailer;
    }

    public function confirm()
    {
        // ...

        $this->mailer->sendRegistrationConfirmedEmail();
    }
}
php symfony observer-pattern symfony5
1个回答
0
投票

事件驱动系统很难维护,因为它在应用程序逻辑中增加了更多抽象。我的意思是,您需要关注哪些事件具有订阅者(如果有)。但这实际上是唯一的缺点,不是服务之间的直接关系。最大的优点是不同的服务是分离的,每个事件可以添加尽可能多的订户。在您提到的情况下,可以存在UserRegisteredEvent,该事件可以使订阅者发送欢迎电子邮件,另一个可以设置其工作场所或对此进行其他操作。

© www.soinside.com 2019 - 2024. All rights reserved.