Code Happy: Events

← Back to Index

Please note that this chapter was written for VERSION 3 of the Laravel PHP Framework.

Events are a way of letting other pieces of code extend your applications in a neat way. Some other applications refer to this type of extension as a 'Hook'. If you are a 'PHP Guru' you might see some resemblances to the 'Observer / Observable' design pattern.

Events may have any number of listeners and firing them can return a varied number of responses. I think the best way to learn will be to see this in action. Let's take a closer look at Events in Laravel.

Fire An Event

<?php

$responses = Event::fire('dinner.time');

In this example we 'trigger', or 'fire' the event dinner.time which alerts all of the listeners of the event that it is time to get your grub on. The $responses variable will contain an array of responses that the listeners of the event will provide, more on that later.

We can also retrieve the first response from an event, rather than all of them. We simply call the first() method instead of fire() and now we receive a single result like this.

<?php

$response = Event::first('dinner.time');

It's worth noting that although we are only receiving one response, all of the events listeners will be informed. This means that the event will be fired just as if it was using the fire() method, but all responses apart from the first will be ignored.

The third option for firing an event is the until() method. This method will fire the event, notifying each listener until the first response that is a 'NON-NULL' value is returned. The first 'NON-NULL' value is then passed to the $response variable.

<?php

$response = Event::until('dinner.time');

Well now that we know how to fire an event, let's have a look at the other end of the spectrum. We need to know how to register ourselves as a listener. We don't want to miss our dinner!

Listen for an Event

To listen for an event we use the... yeah you probably guessed it. The listen() method. We hand it the name of the event that we are looking for as a string, and as the second parameter a closure to be performed when the event has been fired. The result of the closure will be passed back as a response. Let's take a look.

<?php

Event::listen('dinner.time', function() {
    return 'thanks for the grub!';
});

If we now call $val = Event::first('dinner.time'); the value of $val will be thanks for the grub!. Simple as that.

Events With Parameters

Extra information can be passed to a listener from a fired event by passing an array of values to the event closure. Like this..

<?php

$responses = Event::fire('dinner.time', array(1, 2, 3));

We can then add parameters to the closure in our listener to 'catch' these values, like so :

<?php

Event::listen('dinner.time', function($one, $two, $three) {
    return 'thanks for the grub!';
});

Easy as pie! Which coincidentally is what is for dinner.

Laravel Events

Here are the events that can be found inside the Laravel core. Normally you won't have to interact with these, but once you have become a Laravel Guru you may feel the need to bend the framework to your will. Using these events is one such example of doing so.

<?php

Event::listen('laravel.log', function($type, $message){});

A new laravel log entry has been created.

<?php

Event::listen('laravel.query', function($sql, $bindings, $time){});

An SQL query has been performed.

<?php

Event::listen('laravel.done', function($response){});

Laravel's work is done, and the response is ready to be sent.

<?php

Event::listen('404', function(){});

A page could not be found.

and many more.

Note: It is best to prefix your event with the application name to avoid conflicts with other events. This is why all Laravel events start with laravel..

Example Usage

So where will using Events come in handy? Well imagine we have a simple task management application. These types of applications will likely have a User type object to allow our users to login and use the application. User objects can also be created to add more users to the system. Let's attach a Laravel Event to the user creation process..

<?php

$new_user = array(.. user details here ..);
$u = new User($new_user);
$u->save();

Event::fire('myapp.new_user', array($u->id));

As you can see, we pass the new user's id value to the 'myapp.new_user' event so that all event listeners are aware of which user has been created.

Now let's create an extension to our application. The extension should not interfere with the existing code of the application, it could be an extra library, or a bundle, anything outside of the main application.

In our extension we are going to add a prefix to the users name (this is somehow useful to our extension). Let's do this by listening to the user event.

<?php

Event::listen('myapp.new_user', function ($uid) {
    $user = User::find($uid);
    $user->name = 'Myapp_'.$user->name;
    $user->save();
});

We create a listener that receives the user id. Using this we can retrieve the new user from the database and apply the changes.

We have now added some extra functionality to the application without editing its core files. It is the responsibility of the application's author to insert Event triggers or fire() methods within area's of the application that are likely to be extended. Without these events the application's source would have to be modified.

My books are available online for free to encourage learning. However, if you'd like for me to keep writing, then please consider buying a digital copy over at Leanpub.com.

It's available in PDF, ePub, and Kindle format, and contains a bunch of extras that you won't find on the site. I have a full-time job, and I write my books in my spare time. Please consider buying a copy so that I can continue to write new books from the comfort of my sofa!