PHP Observer Method


 

PHP Observer Method

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..

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

0

{

public function onChanged($sender, $args){

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

1

}

} 

$sl = new StudentList();

2

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

$sl->addStudent( "Rose" );

?>

3

Output:

Rose added to Student list

Ads