<?php
require_once 'CartListenerInterface.php';
class Cart
{
private $_items;
private $_listeners;
public function __construct()
{
$this->_items = array();
$this->_listeners = array();
}
public function addItem($id)
{
if (isset($this->_items[$id])) {
$this->_items[$id]++;
} else {
$this->_items[$id] = 1;
}
$this->notify();
}
public function removeItem($id)
{
if (isset($this->_items[$id])) {
$this->_items[$id]--;
} else {
$this->_items[$id] = 0;
}
if ($this->_items[$id] <= 0) {
unset($this->_items[$id]);
}
$this->notify();
}
public function getItems()
{
return $this->_items;
}
public function removeItems()
{
$this->_items = array();
$this->notify();
}
public function hasItem($id)
{
return array_key_exists($id, $this->_items);
}
public function addListener(CartListenerInterface $listener)
{
$this->_listeners[get_class($listener)] = $listener;
}
public function removeListener(CartListenerInterface $listener)
{
unset($this->_listeners[get_class($listener)]);
}
public function notify()
{
foreach ($this->_listeners as $listener) {
$listener->update($this);
}
}
}