Laravel 5 - Confusion between Event Handlers and Listeners

user391986 picture user391986 · May 19, 2015 · Viewed 7.6k times · Source

I'm a bit confused about the different between Events and Listeners.

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.

They work after I define them in Providers\EventServiceProvider.php

protected $listen = [
    UserHasSignedUp::class => [
        SendWelcomeEmail::class,
        SendAdminEmail::class
    ]
];

So what are Listeners?

To me they seem exactly the same thing as Event Handlers?

Answer

Ezequiel Moreno picture Ezequiel Moreno · May 20, 2015

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.

Super simple example:

Somewhere in UserController

Event::fire(new UserHasSignedUp($user)); //UserHasSignedUp is the event being fired

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 can't listen to more than a single event. If you want a class listening to many events, you should take a look to Event Subscribers

Hope it helps.