Events provide a great away to build de-coupled applications, and allow plug-ins to tap into the core of your application without modifying its code. Let's jump right in.
Firing an event couldn't be any easy, just tell the Event class the name of the event you want to fire:
$responses = Event::fire('loaded');
Notice that we assigned the result of the fire method to a variable. This method will return an array containing the responses of all the event's listeners.
Sometimes you may want to fire an event, but just get the first response. Here's how:
$response = Event::first('loaded');
Note: The first method will still fire all of the handlers listening to the event, but will only return the first response.
So, what good are events if nobody is listening? It's simple to register event handlers. Let's take a look:
Event::listen('loaded', function()
{
// I'm executed on the "loaded" event!
});
The Closure we provided to the method will be executed each time the "loaded" event is fired. Simple, huh?
There are several events that are fired by the Laravel core. Here they are:
Event::listen('laravel.started: bundle', function() {});
Event::listen('laravel.query', function($sql, $bindings, $time) {});
Event::listen('laravel.done', function($response) {});