Search
Search Menu

Illuminate Events Library in a Nutshell

Illuminate Events is a another great component that makes up Laravel. it’s a simple observer implementation which allows you to fire events when something happens and then listen in on the event in another part of your application. Below is a quick guide on how to use the events library in any PHP application.

Key Concepts

There are two key concepts to using the Events library:

  • Fire: Action that just happened, e.g. user.signup
  • Listen: Waits for the event action then handles it e.g. on user.signup it might send a signup email

Pull in the Illuminate Events Component

Add the following line as a requirement in your composer.json file:

"illuminate/events": "4.1.*"

Update your composer requirements by issuing:

composer update

IoC Container

Create a new container in your script if you don’t have one:

$app = new \Illuminate\Container\Container;

Define Events in the IoC Container

Register how to build the Events object in your IoC

$app['events'] = $app->share(function($app) {
    return new \Illuminate\Events\Dispatcher($app);
});

Fire new Events

Start publishing events like so, you can add parameters that your listener may need as the second parameter

$app['events']->fire('event.name', array(...));

Listen to Events

Then elsewhere in your code start listening to events, you’ll want to replace the parameters with the ones this event listener needs. Also you don’t need to set the third parameter, which is the event priority, however if you do then use a numeric value.

$app['events']->listen('event.name', function(...your parameters) {
    ... your code
}, event priority);

Wilcard Listeners

You can also use ‘event.*’ to catch all events that start with ‘event.’

Use a Class to listen to an Event

Pass the class you want to handle the Event fire as the second parameter to Event Listener and then ensure the class exists or create one. By default this class would need a handle method, if you would rather use a custom method to handle the event, then use the following format in the second parameter: “ClassName@ClassMethod”.

Questions

If you have any questions please contact me by tweeting at me: @_safeer_