首页 > laravel > Laravel 5.6一个事件和许多可选的听众

Laravel 5.6一个事件和许多可选的听众 (Laravel 5.6 one event and many optional listeners)

问题

在Laravel 5.6

我有一个名为的活动DocumentSend

我有很多听众赞(SendEmailSendNotificationSendSMS),

监听器是可选的(取决于文档类型并由用户定义),现在的问题是:

我如何DocumentSend只用SendSMS侦听器或DocumentSend所有侦听器调用事件?

我希望你能理解我的意思,并告诉我解决问题的最佳方法。

提前致谢

解决方法

嗯,简单的答案是 - 你做不到。当您触发事件时,所有已注册的侦听器都将收听此事件并将启动所有这些事件。

但是,没有什么能阻止您阻止从侦听器运行代码。

例如,您可以像这样触发事件:

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

并定义DocumentSend的构造函数,如下所示:

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

现在在每个监听器中你可以只验证正确的变量,所以例如在SendEmail监听器中handle你可以这样做:

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

  // here your code for sending
}

类似的你可以为其他听众做。

当然这仅是示例 - 您不必使用4个变量。您可以将某些属性设置为$ document,以标记应如何发送。

问题

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

解决方法

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.

相似信息