Websiteentwicklung: PHP: Observer

Aus Wikibooks
Wechseln zu: Navigation, Suche

Implementierung (ab Version 5)[Bearbeiten]

interface Subject{
	public function register_observer(Observer $observer);
	public function remove_observer(Observer $observer);
	public function inform_observers();
}
 
class MySubject implements Subject{
	private $observers = array();
	private $value;
	public function register_observer(Observer $observer){
		$this->observers[] = $observer;
	}
	public function remove_observer(Observer $observer){
		$offset = array_search($observer, $this->observers);
		unset($this->observers[$offset]);
	}
	public function inform_observers(){
		foreach($this->observers as $observer) {
			$observer->update($this->value);
		}
	}
	public function setValue($value){
		$this->value = $value;
		$this->inform_observers();
	}
}
 
interface Observer{
	public function update($value);
}
 
class MyObserver1 implements Observer {
	public function __construct(Subject $subject){
		$subject->register_observer($this);
	}
	public function update($value){
		print "I'm observer 1 and value is ".$value."\n";
	}
}
 
class MyObserver2 implements Observer {
	public function __construct(Subject $subject){
		$subject->register_observer($this);
	}
	public function update($value){
		print "I'm observer 2 and value is ".$value."\n";
	}
}
 
$mySubject = new MySubject();
$myObserver1 = new MyObserver1($mySubject);
$myObserver2 = new MyObserver2($mySubject);
$mySubject->setValue(1);
$mySubject->remove_observer($myObserver1);
$mySubject->setValue(2);
I'm observer 1 and value is 1
I'm observer 2 and value is 1
I'm observer 2 and value is 2