Unlike other SPL interfaces, I'm not finding that this pair of built-in interfaces has any intrinsic value other than to provide a template. It would be nice if Observer can automatically trigger its update()
method any time Subject properties are modified in any way, but this isn't the case. You have to set it up manually.
So to start, you want to separate contrlr
into separate SplSubject and SplObserver classes. Otherwise, for all intents and purposes, it's only notifying itself. model
can actually be the one that implements SplObserver in your case. But really, which class implements which interface would be up to you. Here's just an example of a basic usage...
class Observer implements SplObserver {
function update(SplSubject $subject) {
echo "notified: " . $subject->status . "\n";
}
}
class Subject implements SplSubject {
private $status;
private $observer;
function __construct(SplObserver $observer) {
$this->attach($observer);
}
function __destruct() {
$this->detach($this->observer);
}
function __get($prop) {
return $this->$prop;
}
function __set($prop, $val) {
$this->$prop = $val;
$this->notify();
}
function notify() {
$this->observer->update($this);
}
function attach(SplObserver $observer) {
$this->observer = $observer;
$this->__set("status", "attaching");
}
function detach(SplObserver $observer) {
$this->__set("status", "detaching");
$this->observer = null;
}
}
$observer = new Observer();
$sub1 = new Subject($observer);
$sub1->status = "testing";
$sub2 = new Subject($observer);
unset($sub2);
$sub1->status = "testing again";