<?php
/*
*
* @Author: Zuhair Mirza
* @Implementation Of Oberver Design Pattern in PHP (Practical Example)
* @Date : 15-June-2015
* @Defination : An object is made observable by adding a method that allows
* another object, the observer to get registered. If the observable object gets changed,
* it sends a message to the objects which are registered as observers:
*
*/
interface Observer {
function onChanged($sender, $args);
}
interface Observable {
function addObserver($observer);
}
class CustomerList implements Observable {
private $_observers = array();
public function addCustomer($name) {
foreach ($this->_observers as $obs)
$obs->onChanged($this, $name);
}
public function addObserver($observer) {
$this->_observers [] = $observer;
}
public function getObserver() {
return $this->_observers;
}
}
class CustomerListLogger implements Observer {
public function onChanged($sender, $args) {
echo( "'$args' Customer has been added to the list \n" );
}
}
$ul = new CustomerList();
$ul->addObserver(new CustomerListLogger());
$ul->addCustomer("Zuhair"); // Output : 'Zuhair' Customer has been added to the list
$ul->addCustomer("Mirza"); // Output : 'Mirza' Customer has been added to the list
var_dump($ul->getObserver()); // Output : array(1) { [0]=> object(CustomerListLogger)#2 (0) { } }
/*
*
* @Author: Zuhair Mirza
* @Implementation Of Oberver Design Pattern in PHP (Practical Example)
* @Date : 15-June-2015
* @Defination : An object is made observable by adding a method that allows
* another object, the observer to get registered. If the observable object gets changed,
* it sends a message to the objects which are registered as observers:
*
*/
interface Observer {
function onChanged($sender, $args);
}
interface Observable {
function addObserver($observer);
}
class CustomerList implements Observable {
private $_observers = array();
public function addCustomer($name) {
foreach ($this->_observers as $obs)
$obs->onChanged($this, $name);
}
public function addObserver($observer) {
$this->_observers [] = $observer;
}
public function getObserver() {
return $this->_observers;
}
}
class CustomerListLogger implements Observer {
public function onChanged($sender, $args) {
echo( "'$args' Customer has been added to the list \n" );
}
}
$ul = new CustomerList();
$ul->addObserver(new CustomerListLogger());
$ul->addCustomer("Zuhair"); // Output : 'Zuhair' Customer has been added to the list
$ul->addCustomer("Mirza"); // Output : 'Mirza' Customer has been added to the list
var_dump($ul->getObserver()); // Output : array(1) { [0]=> object(CustomerListLogger)#2 (0) { } }
No comments:
Post a Comment