Last active
November 23, 2017 22:00
-
-
Save sokil/0ba838d7ede936e9c40d to your computer and use it in GitHub Desktop.
PHP SPL Observer pattern
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class Observable implements \SplSubject | |
{ | |
private $_observers = array(); | |
public function notify() | |
{ | |
foreach($this->_observers as $observer) { | |
$observer->update($this); | |
} | |
} | |
public function attach(\SplObserver $observer) | |
{ | |
$this->_observers[] = $observer; | |
return $this; | |
} | |
public function detach(\SplObserver $observer) | |
{ | |
foreach($this->_observers as $i => $iteratedObserver) { | |
if($observer === $iteratedObserver) { | |
unset($this->_observers[$i]); | |
break; | |
} | |
} | |
return $this; | |
} | |
} | |
class Observer implements \SplObserver | |
{ | |
private $_name; | |
public function __construct($name) | |
{ | |
$this->_name = $name; | |
} | |
public function update(\SplSubject $subject) | |
{ | |
echo 'Observer ' . $this->_name . ' called' . PHP_EOL; | |
} | |
} | |
$observable = new Observable; | |
$observer1 = new Observer('A'); | |
$observable->attach($observer1); | |
$observer2 = new Observer('B'); | |
$observable->attach($observer2); | |
$observable->notify(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment