PHP Objects, Patterns and Practice (3rd edition)

(Barry) #1
CHAPTER 11 ■ PERFORMING AND REPRESENTING TASKS

$this->observers = array();


}


function attach( Observer $observer ) {
$this->observers[] = $observer;
}


function detach( Observer $observer ) {
$newobservers = array();
foreach ( $this->observers as $obs ) {
if ( ($obs !== $observer) ) {
$newobservers[]=$obs;
}
}
$this->observers = $newobservers;
}


function notify() {
foreach ( $this->observers as $obs ) {
$obs->update( $this );
}
}
//...


So the Login class manages a list of observer objects. These can be added by a third party using the
attach() method and removed via detach(). The notify() method is called to tell the observers that
something of interest has happened. The method simply loops through the list of observers, calling
update() on each one.
The Login class itself calls notify() from its handleLogin() method.


function handleLogin( $user, $pass, $ip ) {
switch ( rand(1,3) ) {
case 1:
$this->setStatus( self::LOGIN_ACCESS, $user, $ip );
$ret = true; break;
case 2:
$this->setStatus( self::LOGIN_WRONG_PASS, $user, $ip );
$ret = false; break;
case 3:
$this->setStatus( self::LOGIN_USER_UNKNOWN, $user, $ip );
$ret = false; break;
}
$this->notify();
return $ret;
}


Here’s the interface for the Observer class:

interface Observer {
function update( Observable $observable );
}

Free download pdf