PHPGrandMaster
PHPGrandMaster

Reputation: 358

Understanding Constructors for Event Listeners

I created an Event \ Listener by registering the pair in the EventServiceProvider. After running php artisan generate:event Laravel creates the Event and Listener classes in there respected directories.

I notice that if you want to fire an event you need to call the static Event::fire method.

Event::fire( new SomeEventClass($variable));

However I noticed that if you wanted to pass a $variable into the Listener.

You would need to declare $variable as a public property of the class and create a constructor in the Associated Event class so that you can use it in the Listener class, by later passing $variable from $event->variable, otherwise $variable would not work in the Listener class.

 class SomeEventClass extends Event {

    use SerializesModels;

    public $variable;
    /**
     * Create a new event instance.
     *
     * @return void
     */
    public function __construct($variable) {
        $this->variable = $variable;
    }

    /**
     * Get the channels the event should be broadcast on.
     *
     * @return array
     */
    public function broadcastOn() {
        return [];
    }
}

So to re-clarify my question what is "going on under the hood" in this situation.

Upvotes: 0

Views: 2694

Answers (1)

user1669496
user1669496

Reputation: 33058

I don't think there is a lot going on under the hood here, it's a pretty transparent process.

When you fire an event, Laravel will look up all the listeners for that event (via the array in the EventServiceProvider class) and pass the event class to each listener it finds and call the handle method on each listener.

The event class really only does one thing, it holds onto the data for the listeners to eventually use. We set that data to public because that creates a very simple way for the listeners to pull the data they need out of the event class.

Upvotes: 2

Related Questions