Monday, May 12, 2014

PHP Design Patterns - The Observer Pattern

In this case class NoticeBoard is publisher and classes Student and Teacher are subscribers

<?php
class NoticeBoard{
  private $_observers = array();

  public function addNote( $name )  {
    foreach( $this->_observers as $obs )
      $obs->onChanged( $this, $name );
  }

  public function addObserver( $observer )  {
    $this->_observers []= $observer;
  }
}

class Student{
  public function onChanged( $sender, $args )  {
    echo("The ".__CLASS__." is informed '$args' \n" );
  }
}

class Teacher{
  public function onChanged( $sender, $args )  {
    echo( "The ".__CLASS__." is informed '$args' \n" );
  }
}

$s = new Student(); 
$t = new Teacher();

$nb = new NoticeBoard(); 
$nb -> addObserver($s); 
$nb -> addObserver($t);

$nb->addNote('Due storm exams are postponed.');
?>

Result is
The Student is informed 'Due storm exams are postponed.'
The Teacher is informed 'Due storm exams are postponed.'