Laravel 5 - 事件处理程序和侦听器之间的混乱 [英] Laravel 5 - Confusion between Event Handlers and Listeners
问题描述
我对事件和侦听器之间的不同有些困惑。
I'm a bit confused about the different between Events and Listeners.
我了解了可以在事件
下创建事件,然后注册它们,并在 Handlers\Events
中实现处理程序。所以在这里我有事件和事件的处理。
I understood how you can create your events under Events
then register them and implement the Handlers in Handlers\Events
. So here I have events and the handling of events.
他们在 Providers\EventServiceProvider.php
protected $listen = [
UserHasSignedUp::class => [
SendWelcomeEmail::class,
SendAdminEmail::class
]
];
那么什么是听众?
对我来说,他们似乎与事件处理程序完全相同?
To me they seem exactly the same thing as Event Handlers?
推荐答案
在你的例子中, UserHasSignedUp
是一个事件
。 SendWelcomeEmail
和 SendAdminEmail
是两个侦听器等待事件UserHasSignedUp被触发,他们应该实现所需的业务逻辑在 handle
方法。
In your example UserHasSignedUp
is an Event
. SendWelcomeEmail
and SendAdminEmail
are two listeners "waiting" for the event UserHasSignedUp to be fired and they should implement the required business logic at handle
method of each one.
超简单的例子:
UserController中的某个地方
Somewhere in UserController
Event::fire(new UserHasSignedUp($user)); //UserHasSignedUp is the event being fired
SendWelcomeEmail类
SendWelcomeEmail class
class SendWelcomeEmail //this is the listener class
{
public function handle(UserHasSignedUp $event) //this is the "handler method"
{
//send an email
}
}
您可以看到,每个事件可以有多个侦听器,但是一个侦听器不能听多于一个事件。
如果您想要一个听许多事件的班级,您应该查看活动订阅者
As you can see, each event can have multiple listeners, but a listener cant listen to more than a single event. If you want a class listening to many events, you should take a look to Event Subscribers
希望它有帮助。
这篇关于Laravel 5 - 事件处理程序和侦听器之间的混乱的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!