-1

I have a Mailer service which is responsible to create and send emails. I also have Registration service which confirm a user registration.

What are the benefits to dispatch a custom event, subscribe to it and then send the email with the Mailerservice instead of just using the Mailer service in the Registration by injecting it?

I'm a little bit confused. The first one seems to be harder to maintain but I've seeing it too many time that maybe I should consider it.

In other words. Should I do this :

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();
    }
}

Or this :

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

    public function confirm()
    {
        // ...

        $this->mailer->sendRegistrationConfirmedEmail();
    }
}
Benjamin
  • 341
  • 4
  • 15

1 Answers1

1

The event driven system is a bit hard to maintain because it adds little bit more abstraction in the application logic. What I mean with that is you need to follow which events have subscribers if any. But actually this is the only disadvantage /not direct relation between services/. The big advantage is that the different services are decoupled and you can add as many subscribers per event. In the case which you mentioned the there can be UserRegisteredEvent which can have subscriber for sending a welcome email and another which setup his workplace or do something else on this even.

Alexander Dimitrov
  • 944
  • 1
  • 6
  • 17