CHAPTER 11 ■ PERFORMING AND REPRESENTING TASKS
Figure 11–6. The Observer pattern
PHP provides built-in support for the Observer pattern through the bundled SPL (Standard PHP
Library) extension. The SPL is a set of tools that help with common largely object-oriented problems.
The Observer aspect of this OO Swiss Army knife consists of three elements: SplObserver, SplSubject,
and SplObjectStorage. SplObserver and SplSubject are interfaces and exactly parallel the Observer and
Observable interfaces shown in this section’s example. SplObjectStorage is a utility class designed to
provide improved storage and removal of objects. Here’s an edited version of the Observer
implementation:
class Login implements SplSubject {
private $storage;
//...
function __construct() {
$this->storage = new SplObjectStorage();
}
function attach( SplObserver $observer ) {
$this->storage->attach( $observer );
}
function detach( SplObserver $observer ) {
$this->storage->detach( $observer );
}