Skip to content

Instantly share code, notes, and snippets.

@mt3o
Created June 27, 2013 10:52
Show Gist options
  • Save mt3o/5875600 to your computer and use it in GitHub Desktop.
Save mt3o/5875600 to your computer and use it in GitHub Desktop.
Observers in PHP with SPL
<?php
class MyObserver implements SplObserver {
public function update(SplSubject $subject) {
echo __CLASS__ . ' - ' . $subject->getName();
}
}
class MySubject implements SplSubject {
private $_observers;
private $_name;
public function __construct($name) {
$this->_observers = new SplObjectStorage();
$this->_name = $name;
}
public function attach(SplObserver $observer) {
$this->_observers->attach($observer);
}
public function detach(SplObserver $observer) {
$this->_observers->detach($observer);
}
public function notify() {
foreach ($this->_observers as $observer) {
$observer->update($this);
}
}
public function getName() {
return $this->_name;
}
}
$observer = new MyObserver();
$subject = new MySubject("test");
$subject->attach($observer);
$subject->notify();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment