Patterns For PHP
Index Patterns News Forums

Observer

From Patterns For PHP

Introduction

The Observer pattern is like a newspaper subscription. You have a subject, which is the object that changes its state (in our example is the newspaper) and a observer, which is the object that receives these changes (the subscriber).

Implementing the Observer Pattern

First I'll create the subject interface.

php
interface Subject {
	public function registerObserver(Observer $o);
	public function removeObserver(Observer $o);
	public function notifyObservers();
}


Now I'll create the observer interface.

php
interface Observer {
	public function update($news);
}


Now I'll create the Newspaper class which implements the Subject interface.

php
class Newspaper implements Subject {
	private $observers = array();
	private $news;
	
	public function __construct() {
	}
	
	public function registerObserver(Observer $o) {
		$this->observers[] = $o;
	}
	
	public function removeObserver(Observer $o) {
		uns
1000
et($this->observers[array_search($o, $this->observers)]);
	}
	
	public function notifyObservers()
1000
 {
		foreach($this->observers as $observer) {
			$observer->update($this->news);
		}
	}
	
	public function setNewNews($news) {
		$this->news = $news;
		$this->notifyObservers();
	}
}


Now the Subscriber class which implements the Observer interface.

php
class Subscriber implements Observer {
	private $newspaper;
	
	public function __construct(Subject $newspaper) {
		$this->newspaper = $newspaper;
		$this->newspaper->registerObserver($this
1000
);
	}
	
	public function cancelSubscript() {
		$this->newspaper->removeObserver($this);
	}
	
	public function update($news) {
		echo date("h:i:s") . ": " . $news;
	}
}


And finally I'll use all of this.

php
$newspaper = new Newspaper();
$subscriber1 = new Subscriber($newspaper);
$subscriber2 = new Subscriber($newspaper);
$newspaper->setNewNews("Today is tuesday.");
$newspaper->setNewNews("So, tomorrow will be wednesday.");
$subscriber1->cancelSubscript();
$newspaper->setNewNews("So, the day after tomorrow will be thursday.");

Conclusion

You can put another classes that implements Observer and all of them will receive the last news!

Retrieved from "/wiki/Observer"
MediaWiki
GNU Free Documentation License 1.2