Created
September 16, 2012 06:53
-
-
Save ackintosh/3731335 to your computer and use it in GitHub Desktop.
Sample of observer pattern using PHP5.4 trait.
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
trait Subject | |
{ | |
public function initListeners() | |
{ | |
$this->listeners = array(); | |
} | |
public function addListener($listener) | |
{ | |
$this->listeners[] = $listener; | |
} | |
public function notify() | |
{ | |
foreach ($this->listeners as $listener) { | |
$listener->update($this); | |
} | |
} | |
} | |
class Cart | |
{ | |
use Subject; | |
public function addItem($item){ | |
$this->notify(); | |
} | |
} | |
interface Listener | |
{ | |
public function update($cart); | |
} | |
class CartListener1 implements Listener | |
{ | |
public function update($cart) | |
{ | |
echo "update 1!" . PHP_EOL; | |
} | |
} | |
class CartListener2 implements Listener | |
{ | |
public function update($cart) | |
{ | |
echo "update 2!!" . PHP_EOL; | |
} | |
} | |
$cart = new Cart(); | |
$cart->initListeners(); | |
$cart->addListener(new CartListener1()); | |
$cart->addListener(new CartListener2()); | |
$cart->addItem('item'); | |
/* | |
update 1! | |
update 2!! | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment