Tuesday, July 12, 2011

Observer Design Pattern example using PHP

The observer pattern is a software design pattern in which an object (called the subject object) maintains a list of its dependents (called observers) and notifies them automatically of any state changes, usually by calling one of their methods. It is mainly used to implement distributed event handling systems.
  • The Observer pattern defines an one-to-many dependency between a subject object and any number of observer objects so that when the subject object changes state, all its observer objects are notified and updated automatically.
  • The Observer pattern essentially allows an unlimited number of objects to observe or listen to events in the observed object (or subject) by registering themselves. After observers are registered to an event, the subject will notify them when the event is fired.
  • The subject handles this by storing an observer collection and iterating through it when the event occurs in order to notify each observer.
  • Observer Pattern registers observers with a subject.
  • You might have multiple observers. Subject must keep a list of registered observers and when event occurs it fires (provides notification) all registered observers.
  • Unregister also possible when we do not need any observer.

Example using Observer Design Pattern:
interface IObserver {
    function onChanged($sender, $args);

interface IObservable {
    function addObserver($observer);

class UserList implements IObservable {
    private $_observers = array();

    public function addCustomer($name) {
        foreach( $this->_observers as $obs )          
            $obs->onChanged( $this, $name );
    public function addObserver( $observer ) {
        $this->_observers []= $observer;

class UserListLogger implements IObserver {       
    public function onChanged( $sender, $args ) {
        echo( "'$args' notifies  UserListLogger <br>" );           

class AuditLogger implements IObserver {
    public function onChanged( $sender, $args ) {
        echo( "'$args' notifies  AuditLogger <br>" );       

$ul = new UserList();
$ul->addObserver(new UserListLogger() );
$ul->addObserver(new AuditLogger() );

$ul->addCustomer("Jack" );
$ul->addCustomer("John" );

Source:  From lecture notes of Design and Development Open Multi-tier Application