PEAR is archived and read-only

This mirror preserves historical PEAR package releases and metadata so existing references remain available.

Home » Event » Event_Dispatcher » Manual

Dispatch notifications using PHP callbacks

Introduction

Introduction – Introduction to Event_Dispatcher

Introduction to Event_Dispatcher

Event_Dispatcher acts as a notification dispatch table. It is used to notify other objects of interesting things. This information is encapsulated in Event_Notification objects.

Client objects register themselves with the Event_Dispatcher as observers of specific notifications posted by other objects. When an event occurs, an object posts an appropriate notification to the Event_Dispatcher. The Event_Dispatcher dispatches a message to each registered observer, passing the notification as the sole argument.

Event_Dispatchers allows you to use event bubbling similar to JavaScript's event management. If an event is not handled by the dispatcher that triggered the event, it may bubble up to the next dispatcher.

Examples

Examples – Examples for the usage of Event_Dispatcher

Examples usage of Event_Dispatcher

The following examples show you how to use Event_Dispatcher to create more flexible applications.

Basic example

<?php
require_once 'Event/Dispatcher.php';
    
/**
 * Dummy class that simulated authentication
 */
class Auth
{
    var $_dispatcher = null;
    var $_user;
    
    function Auth(&$dispatcher)
    {
         $this->_dispatcher = &$dispatcher;
    }
    
    function login($username, $password)
    {
        // Your code that authenticates goes here
        // ....
        // imagine $this->_user contains a User object
        
        $this->_dispatcher->post($this->_user, 'onLogin');
    }
}

function logAuth(&$notification)
{
    $user = &$notification->getNotificationObject();
    $username = $user->getUsername();
    
    // write logfile
    error_log("$username logged in.", 3, '/tmp/auth.log');
}

$dispatcher = &Event_Dispatcher::getInstance();

// catch all onLogin events to write a logfile
$dispatcher->addObserver('logAuth', 'onLogin');

$auth = &new Auth($dispatcher);

// simulate login
$auth->login($_GET['user'], $_GET['pass']);
?>

In this example, Event_Dispatcher is used to allow observers to hook into the authentication process. Whenever a user authenticates, a notification onLogin is sent.

This can be used to write logfiles or block the application for other users.

Cancelling notifications

<?php
require_once 'Event/Dispatcher.php';
    
/**
 * Dummy class that simulated authentication
 */
class Auth
{
    var $_dispatcher = null;
    var $_user;
    
    function Auth(&$dispatcher)
    {
         $this->_dispatcher = &$dispatcher;
    }
    
    function login($username, $password)
    {
        // Your code that authenticates goes here
        // ....
        // imagine $this->_user contains a User object
        
        $notification = $this->_dispatcher->post($this->_user, 'onLogin');
        
        if ($notification->isNotificationCancelled()) {
            echo "You are not allowed to login";
            $this->_user->logout();
        }
    }
}

function logAuth(&$notification)
{
    $user = &$notification->getNotificationObject();
    $username = $user->getUsername();
    
    // If a special user authenticated, cancel
    // the notification
    if ($username === 'foo') {
        $notification->cancelNotification();
    } else {
        // write logfile
        error_log("$username logged in.", 3, '/tmp/auth.log');
    }
}

$dispatcher = &Event_Dispatcher::getInstance();

// catch all onLogin events to write a logfile
$dispatcher->addObserver('logAuth', 'onLogin');

$auth = &new Auth($dispatcher);

// simulate login
$auth->login($_GET['user'], $_GET['pass']);
?>

In this case, the cancelNotification() method is used to cancel the notification if a certain user tries to authenticate.

The login method has been changed as well to check whether the notification has been cancelled and to take the necessary steps.

This allows you to add some flexible rules to your authentication system.

Event_Dispatcher::getInstance

Event_Dispatcher::getInstance() – Create a new Event_Dispatcher object

Synopsis

require_once 'Event/Dispatcher.php';

object Event_Dispatcher Event_Dispatcher::getInstance ( string $name = '__default' )

Description

Create a new Event_Dispatcher object.

As Event_Dispatcher uses the singleton pattern, you must not use the new operator to create a new instance of Event_Dispatcher, but use getInstance() instead.

If you need more than one instance of Event_Dispatcher, pass different names to the method.

Parameter

Return value

object Event_Dispatcher Event_Dispatcher instance

Note

This function should be called statically.

Event_Dispatcher::getName

Event_Dispatcher::getName() – Get the name of the dispatcher.

Synopsis

require_once 'Event/Dispatcher.php';

string Event_Dispatcher::getName ( )

Description

Get the name of the dispatcher.

The name of the dispatcher is used as a unique identifier. This is important for the methods getInstance() and removeNestedDispatcher().

Return value

string name of the dispatcher

Note

This function can not be called statically.

Event_Dispatcher::addObserver

Event_Dispatcher::addObserver() – Add a new observer.

Synopsis

require_once 'Event/Dispatcher.php';

void Event_Dispatcher::addObserver ( mixed $callback , string $nName = EVENT_DISPATCHER_GLOBAL , string $class = '' )

Description

Adds a new observer to the dispatcher.

Observers are PHP callbacks. That means you may either pass a function name as a string or an array containing an object or class and a method to call.

The callback is used as a signature for the observer, which allows you to remove it by passing the exact same parameters to removeObserver().

Parameter

Return value

void

Note

This function can not be called statically.

Event_Dispatcher::removeObserver

Event_Dispatcher::removeObserver() – Remove an observer.

Synopsis

require_once 'Event/Dispatcher.php';

bool Event_Dispatcher::removeObserver ( mixed $callback , string $nName = EVENT_DISPATCHER_GLOBAL , string $class = '' )

Description

Remove an observer from dispatcher.

To remove an observer, specify the same parameters as used in the call to addObserver().

Parameter

Return value

bool TRUE if the observer could be removed, FALSE otherwise

Note

This function can not be called statically.

Event_Dispatcher::setNotificationClass

Event_Dispatcher::setNotificationClass() – Set the class that is used as notification.

Synopsis

require_once 'Event/Dispatcher.php';

bool Event_Dispatcher::setNotificationClass ( string $class )

Description

Set the name of the class that will be used as a notification object when post() is called.

You may call this method on an object to change it for a single dispatcher or statically, to set the default for all dispatchers that will be created.

Parameter

Return value

This method always returns true.

Note

This function can be called statically.

Event_Dispatcher::post

Event_Dispatcher::post() – Post a notification.

Synopsis

require_once 'Event/Dispatcher.php';

object Event_Notification Event_Dispatcher::post ( object &$object , string $nName , mixed $info = array() , bool $pending = true , bool $bubble = true )

Description

Post a new notification to all observers.

Parameter

Return value

object Event_Notification The notification object.

Note

This function can not be called statically.

Event_Dispatcher::addNestedDispatcher

Event_Dispatcher::addNestedDispatcher() – Add a nested dispatcher.

Synopsis

require_once 'Event/Dispatcher.php';

void Event_Dispatcher::addNestedDispatcher ( object Event_Dispatcher &$dispatcher )

Description

Adds a nested dispatcher to the dispatcher.

Nested dispatchers allow you to create event bubbling like it is implemented in Javascript. After an event has been posted to all observers of the dispatcher, it will be broadcasted to all nested dispatchers.

If you have one dispatcher that dispatches events of a component in your framework and one dispatcher that dispatches global events that are triggered by the framework itself it could make sense that you nest these dispatchers, so that events posted by the component dispatcher will also be broadcasted to the global dispatcher.

Parameter

Return value

void

Note

This function can not be called statically.

Event_Dispatcher::removeNestedDispatcher

Event_Dispatcher::removeNestedDispatcher() – Remove a nested dispatcher.

Synopsis

require_once 'Event/Dispatcher.php';

boolean Event_Dispatcher::removeNestedDispatcher ( object Event_Dispatcher &$dispatcher )

Description

Removes a nested dispatcher from the dispatcher.

To remove a dispatcher from the list of nested dispatcher, just pass the same object to removeNestedDispatcher().

Parameter

Return value

boolean TRUE if the dispatcher could be removed, FALSE otherwise.

Note

This function can not be called statically.

Event_Notification

Event_Notification – Container class for notifications.

Description

The Event_Notification class acts as a container for event information. It provides some setters and getters to access the contained information.

If you need to store additional information about the events or provide additional features, you may change the class that is used by Event_Dispatcher, but it is recommended to extend Event_Notification.

Event_Notification::Event_Notification

Event_Notification::Event_Notification() – Create a new notification object.

Synopsis

require_once 'Event/Notification.php';

object Event_Notification Event_Notification::Event_Notifcation ( object &$object , string $nName , mixed $info = array() )

Description

Constructor of the Event_Notification class.

In most cases, you will not need to create the notification objects yourself, as this is done automatically by the Event_Dispatcher::post() method..

Parameter

Return value

string name of the notification

Note

This function can not be called statically.

Event_Notification::getNotificationName

Event_Notification::getNotificationName() – Get the name of the notification.

Synopsis

require_once 'Event/Notification.php';

string Event_Notification::getNotificationName ( )

Description

Get the name of the notification.

Return value

string name of the notification

Note

This function can not be called statically.

Event_Notification::getNotificationObject

Event_Notification::getNotificationObject() – Get the object that sent the notification.

Synopsis

require_once 'Event/Notification.php';

object &Event_Notification::getNotificationObject ( )

Description

Get a reference to the object that sent the notification.

Return value

object sender of the notification

Note

This function can not be called statically.

Event_Notification::getNotificationInfo

Event_Notification::getNotificationInfo() – Get additional information from the notification.

Synopsis

require_once 'Event/Notification.php';

mixed Event_Notification::getNotificationInfo ( )

Description

Get additional information that has been stored in the notification.

Return value

mixed additional information.

Note

This function can not be called statically.

Event_Notification::getNotificationCount

Event_Notification::getNotificationCount() – Get number of observers notified.

Synopsis

require_once 'Event/Notification.php';

int Event_Notification::getNotificationCount ( )

Description

Retrieves the amount of observers that have been notified by the notification.

Return value

int number of observers notified.

Note

This function can not be called statically.

Event_Notification::cancelNotification

Event_Notification::cancelNotification() – Cancel the notification.

Synopsis

require_once 'Event/Notification.php';

void Event_Notification::cancelNotification ( )

Description

Cancels the notification.

If a notification is cancelled, no more observers will be notified by this notification.

Return value

void

Note

This function can not be called statically.

Event_Notification::isNotificationCancelled

Event_Notification::isNotificationCancelled() – Check, whether notification has been cancelled.

Synopsis

require_once 'Event/Notification.php';

bool Event_Notification::isNotificationCancelled ( )

Description

Checks, whether the notification has been cancelled.

Return value

bool TRUE if the notification has been cancelled, FALSE otherwise.

Note

This function can not be called statically.