Skip to content

Instantly share code, notes, and snippets.

@ackintosh
Created September 16, 2012 06:53
Show Gist options
  • Save ackintosh/3731335 to your computer and use it in GitHub Desktop.
Save ackintosh/3731335 to your computer and use it in GitHub Desktop.
Sample of observer pattern using PHP5.4 trait.
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