Share on Google+Share on Google+

PHP Observer Method

Advertisement
In this pattern one object make itself observable and other objects observed it. The object which is observed is called subject. When the observable object changes it passes some message to the observer and the observer uses those message according to their need..

The PHP Observer Pattern:

In the previous tutorial on Factory method we have studied about tight coupling and the drawbacks of the tight coupling and how to avoid it using Factory method, Observer method works the same. This method is also known as Dependents, Publish-Subscribe, Model-View.

In this pattern one object make itself observable and other objects observed it. The object which is observed is called subject. When the observable object changes it passes some message to the observer and the observer uses those message according to their need.

This pattern is useful for dynamic relationships between objects, we can add a new object when the program is running.

For example many applications (like spreadsheet) have data model and whenever we change the data model, it reflects in the overall application.

Benefit of this pattern is that it reduces the degree of coupling. The subject does not need to know much about the observer rather it allows the observer to subscribe and whenever and whatever changes occur subject passes the message to each of it's observer object.  

PHP Observer Method Example:

<?php

interface Observer

{

function onChanged($sender, $args);

}

interface Observable

{

function addObserver($observer);

} 

class StudentList implements Observable

{

private $_observers = array();

public function addStudent( $name )

{

foreach( $this->_observers as $obs )

$obs->onChanged( $this, $name );

}

public function addObserver( $observer )

{

$this->_observers []= $observer;

}

} 

class StudentListLogger implements Observer

{

public function onChanged($sender, $args){

echo ("$args added to Student list\n");

}

} 

$sl = new StudentList();

$sl->addObserver( new StudentListLogger() );

$sl->addStudent( "Rose" );

?>

Output:

Rose added to Student list

Advertisements

Posted on: February 26, 2010 If you enjoyed this post then why not add us on Google+? Add us to your Circles

Share this Tutorial Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.