Implementing Singleton
Implementing Observer

The Observer Pattern

The observer pattern, also known as subject-observer and listener, is a more complicated but very prevalent and useful pattern. Anyone who has done event handling in Java knows this pattern, every kind of event listener is an observer to one subject or another - the keyboard, a window, a mouse, etc.

The pattern describes how to attach any number of observers to a subject, which can then act on events that occur involving the subject. For example, this pattern is available in the PEAR Log:: package, allowing you to monitor log data with an observer object and take action - such as sending an email page on any critical errors - on certain kinds of log messages.

Here's a simple usage of this implementation of the observer pattern:


require_once 'Log.php';

$logger Log::singleton('file''/tmp/example.log''php', array());
$observer = new Log_observer_pageme(LOG_EMERG);

// Program logic happens here

That's it. Assuming that we've written the Log_observer_pageme class correctly, any critical errors will be emailed to our system administrator's pager; everything else will be logged as normal.