2

in Laravel 5.6

I have an event named DocumentSend,

And i have many Listeners Like (SendEmail, SendNotification, SendSMS),

listeners are optional (depends on document type and defined by user), now the question is:

How can i call for example DocumentSend event with just SendSMS listener or DocumentSend with all the listeners?

I hope you get my mean,and tell me the best practice for my issue.

Thanks in advance

Hamed Yarandi
  • 1,085
  • 1
  • 12
  • 21
  • I have already started thinking about using interfaces. I think you can create a single interface that would be a generic listener then set a property as condition to check when the interface is implemented, then you can manually execute them based on that property. What do you think? – Oluwatobi Samuel Omisakin Jul 22 '18 at 08:38

1 Answers1

4

Well, the simple answers is - you can't. When you fire event all registered listeners will listen to this event and all of them will be launched.

However nothing stops you to prevent running code from listener.

For example you can fire event like this:

event(new DocumentSend($document, true, false, false));

and define constructor of DocumentSend like this:

public function __construct($document, $sendEmail, $sendNotification, $sendSms)
{
    $this->document = $document;
    $this->sendEmail = $sendEmail;
    $this->sendNotification = $sendNotification;
    $this->sendSms = $sendSms;
}

and now in each listener you can just verify correct variable, so for example in SendEmail listener in handle you can do it like this:

public function handle(DocumentSend $event)
{
   if (!$event->sendSms) {
     return;
   }

  // here your code for sending
}

similar you can do for other listeners.

Of course this is just example - you don't have to use 4 variables. You can set some properties to $document only to mark how it should be sent.

Marcin Nabiałek
  • 109,655
  • 42
  • 258
  • 291
  • Thanks for your response, what about [Event Subscribers](https://laravel.com/docs/5.6/events#event-subscribers) – Hamed Yarandi Jul 22 '18 at 08:36
  • I've never used them but probably you also cannot make decisions in there assuming listening is related to document. However in case if it depends on authenticated user it might be possible but then you need give a try. – Marcin Nabiałek Jul 22 '18 at 08:40