Events

The event API offers a fire and forget approach to emitting events in an application. In other words, events inform the application when an action has occurred, while remaining unaware of which modules acted on the event, if any at all. This allows custom modules to respond to certain events without extending existing modules.

Usage Example

Consider a member registration module. This module is pretty generic, and each client may desire slightly varied behavior for their application. One client may want an account activation email to be sent to the end user. Another client may want a text message to be sent, or nothing at all.

Instead of extending the member's module, you can simply create your own module, then create listeners for the user registration event. In your listeners, you would define the controller method to be executed when the event occurs, and that is where your "send email" code would reside.

Listening for an Event

Events listeners must be defined inside the init() method of a module's configuration file. The listener below waits for the members.signup_complete event to occur. When the event is triggered, the sendSignUpEmail method will be executed from the MembersEventsController class.

<?php
namespace \sa\Members;

use sa\application\moduleConfig;
use sa\application\Event;

class MembersConfig extends moduleConfig {
    public static function init() {
        Event::listen('members.signup_complete', 'MembersEventsController@sendSignUpEmail');
    }
}

Event::listen(​action, ​name)

Parameter

Type

Description

$event

string

The name of an event.

$action

string

The controller and method to be executed when the event is emitted. controller@method.

$priority

int

The priority of the listener. Listeners with higher valued priorities will be executed before others.

$name

string

A unique name for the listener. These are necessary to override or remove a module's event listener. Simply create a custom module with the same event listener of the same name to change its behavior.

Fire an Event

Executing an event is simple.

<?php
class MembersSignUpController extends controller {
    public function signUp() {
        // <sign up implementation>
        
        $data = array(
            'first_name' => 'John',
            'last_name'  => 'Doe',
            'email'      => 'john.doe@example.com'
        );
        
        Event::fire('members.signup_complete', $data);
    }
}

Fire(​data)

Parameter

Type

Description

$event

string

The name of an event.

$data

array

The data to be sent with the event.

Last updated