Design Pattern: Observer

The behavioural design pattern Observer allows to automatically update one-to-many dependences.

Structure: an object (Hence: $subject) contains a list of observer references, and provides a method notify() that invoke update() of every observer. Also observers have a reference to $subject, used inside update().
Commonly used to event handling (listeners) and login issues.
Implementation in PHP5:
Define a class Subject:
  • private $observersArray // array of Observer objects
  • attach(Observer $ob) and detach(Observer $ob)
    // add/remove observer $ob to/from $observersArray
  • notify() // call the method update() of every observer attached (in $observersArray)

Define one (or more) class Observer that contain(s):
  • reference (private properties) to Subject
  • __construct($subject) // assign the object to the private properties
  • update() // do sth. on referenced Subject. Automatically invoked from subjects that have this observer attached


//instantiate subject
$s = new Subject();

//create 2 observers
$obs1 = new Observer($s, ...);
$obs2 = new Observer($s, ...);

//attach N observers to the subject

//change something in $s

// to update all the observers attached: only call notify()
// All the N observers will be updated.