Triggering Events

An event is triggered in Recite CMS using the Application_Event class. You can associate any data as required with the event. Additionally, you can receive data back from observers.

To create a new event, instantiate the Application_Event class. This class accepts as its sole argument to the constructor the name of the event. You can then call the trigger() method to trigger the event.

Example 6.1. Creating and triggering an event

<?php
    $event = new Application_Event('/some/sample/event');
    $event->trigger();
?>

At this point, all observers for this event will be triggered. There is no defined order of execution for these observers.

Including Data With An Event

You can include data with an event using the set() method. This method accepts the name of the value as its first argument and the value as its second argument. Observers can then access this data.

Example 6.2. Including data with an event

<?php
    $event = new Application_Event('/some/sample/event');
    $event->set('email', 'foo@example.com')
          ->trigger();
?>

Handling Data Returned by Observers

It is possible to trigger events that expect data to be returned. When triggering an event, you can specify that you expect return data. This results in the event manager returning to you any data returned from all observers.

To do so, call the responds() method. This will result in an instance of Application_Event_ResponseCollection being returned from the call to trigger().

Example 6.3. Receiving a response from an event

<?php
    $event = new Application_Event('/some/sample/event');
    $event->responds();
    
    $responseCollection = $event->trigger();
?>

You can then make use of the response data as required. To do so, call the getResponses() method. This returns an array of Application_Event_Response. Each instance corresponds to a single observer.

Note

Not every observer is guaranteed to send back a response.

Each response can have any amount of data associated with it (each value indexed by a unique name). You can retrieve any value by calling the get() method, or you can retrieve all of the data using getData()

If the given value doesn't exist in the response, null is returned.

Example 6.4. Using an event response

<?php
    $event = new Application_Event('/some/sample/event');
    $event->responds();
    
    $responseCollection = $event->trigger();
    
    foreach ($responseCollection->getResponses() as $response) {
        $response->get('foo'); // get the foo value from a response
    }
?>