IAM

ARTICLE

Event System for Kohana using Hooks

Hooks is a Kohana module implementing a simple event-listener system. Functions may be registered on events which can be fired throughout the application.

Introduction

When developing web applications with Kohana there are many occasions where an event-listener system may be useful. Hooks is a Kohana module designed to simplify the creation of modular applications. Different parts of the applications — modules, plugins etc. — may register on so called hooks. These hooks can be fired at some point in the application such that all registered functions are called. The module is available on GitHub:

Hooks on GitHub

Usage

Hooks are identified by strings. I prefer a dotted lowercase notation like template.scripts or user.created where the names describe the location of the hook within the application.

A hook does not need to be created. It is created automatically when the first action is registered and may be fired even if no action have been registered:

Hooks::register('user.created', function() {
  echo 'Successfully created user.';
});

Any function accepted by call_user_func_array may be registered, this also includes inline functions as shown above.

To run all functions registered on a specific hook, we simply call the fire method:

Hooks::fire('user.created');

We may want to pass additional arguments to all the functions which are called when a hook is fired. Arguments depending on the event may be passed as array to the fire method:

Hooks::register('user.created', function($user) {
  echo 'Successfully created user: ' . $user->first_name . ' ' $user->last_name;
});
// ...
Hooks::fire('user.created', array($user));

There may also be fixed arguments which are already known when the function is registered. We can add these parameters when registering the function:

Hooks::register('user.created', function($currentUser, $newUser) {
  echo $currentUser->first_name . ' ' . $currentUser->last_name ' created a new user: ' . $user->first_name . ' ' $user->last_name;
}, array($currentUser));
// ...
Hooks::fire('user.created', array($newUser));

As seen above the parameters added during registration of the function are passed first. To be precise the parameter arrays are simply merged by array_merge.

What is your opinion on this article? Let me know your thoughts on Twitter @davidstutz92 or LinkedIn in/davidstutz92.