Skip to content

Instantly share code, notes, and snippets.

@frankmayer
Forked from boxers999/gist:1216045
Created October 26, 2013 17:30
Show Gist options
  • Save frankmayer/7172245 to your computer and use it in GitHub Desktop.
Save frankmayer/7172245 to your computer and use it in GitHub Desktop.
<?php
class DemoSubject implements SplSubject{
private $observer, $value;
public function __construct(){
$this->observers = array();
}
public function attach(SplObserver $observer){
$this->observers[] = $observer;
}
public function detach(SplObserver $observer){
if(($idx = array_search($observer, $this->observers, true)) !== false){
unset($this->observers[$idx]);
}
}
public function notify(){
foreach($this->observers as $observer){
$observer->update($this);
}
}
public function setValue($value){
$this->value = $value;
$this->notify();
}
public function getValue(){
return $this->value;
}
}
class DemoObserver implements SplObserver {
public function update(SplSubject $subject){
echo 'This is the value :- '. $subject->getValue();
}
}
$subject = new DemoSubject();
$observer = new DemoObserver();
$subject->attach($observer);
$subject->setValue(5);
$subject->detach($observer);
$subject->setValue(10);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment