Introduction (Previous) (Next) Event_Dispatcher::getInstance

View this page in Last updated: Mon, 02 Jul 2007
English | Dutch | French | German | Hungarian | Japanese | Polish | Russian | Spanish | Plain HTML

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.

Пример 38-2. 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.

Introduction (Previous) (Next) Event_Dispatcher::getInstance

Download Documentation Last updated: Mon, 02 Jul 2007
Do you think that something on this page is wrong? Please file a bug report or add a note.
User Notes:
There are no user contributed notes for this page.