contents); } public function addItem(Item $item) { // get the ID of the item $id = $item->getId(); if(!$id ) { throw new Eeception('The cart requires a valid key for items'); } if(isset($this->contents[$id])) { $this->updateItems($item, $this->contents[$item]['qty'] + 1); } else { $this->contents[$id] = array('item' => $item, 'qty' => 1); $this->ids[] = $id; } } public function updateItem(Item $item, $qty) { // need item id $uid = $item->getId(); //delete or update accordingly if($qty === 0) { $this->deleteItem($item); } elseif ( ($qty > 0) && ($qty != $this->contents[$id]['qty'])) { $this->contents[$id]['qty'] = $qty; } } // end up update item public function deleteItem(Item $item) { $id = $item->getId(); if (isset($this->contents[$id])) { unset($this->contentss[$id]); $index = array_search($id, $this->ids); unset($this->ids[$index]); $this->ids = array_value($this->ids); } } public function count() { return count($this->contents); } public function key() { return $this->position; } public function next() { $this->position++; } public function rewind() { $this->position = 0; } public function valid() { return (isset($this->ids[$this->position])); } public function current() { $index = $this->ids[$this->position]; return $this->items[$index]; } } class Item { protected $id; public function getId() { return $this->id; } }