Using Events

Events allow you to override or extend the standard functionality of PHPR and other modules. This methodology is sometimes referred to as Hooks and Triggers. To use events you must start with a module, you can learn to create a module by reading the Creating a Module article.

Subscribing to Events

Subscribing to an event, also known as hooking on to an event, allows you to inject code in to an exisiting workflow. For example, when a user is first registered you might want to add them to a 3rd party mailing list, this could be achieved by subscribing to the user:onUserCreated event. The definitions for event subscriptions are located in the module info class file using the subscribe_events() method.  For example:

public function subscribe_events()
{
	Phpr::$events->add_event('user:onUserCreated', $this, 'on_user_create');
}

This code subscribes to the user:onUserCreated event and when it is triggered the on_new_user handler method (specified in the third parameter) will be called. This handler method must be defined in the same class and it can be named anything. Below is an example of this:

public function on_user_create($user)
{
	// Code to register $user->email to mailing list
}

Declaring Events

You can declare events, also known as triggering an event, anywhere in your code. Triggers are defined using the fire_event() method and can have unlimited parameters. Below is an example:

Phpr::$events->fire_event('mymodule:myCustomEvent', 'first parameter', 'second parameter', 'third parameter');

Once this event has been subscribed to, the parameters are available in the handler method. For example:

public function subscribe_events()
{
	Phpr::$events->add_event('mymodule:myCustomEvent', $this, 'on_custom_event');
}

public function on_custom_event($param1, $param2, $param3)
{	
	// Parameters: first parameter second parameter third parameter
	echo 'Parameters: '.$param1.' '.$param2.' '.$param3;
}