E-Commerce shopping class cart


SUBMITTED BY: Guest

DATE: May 10, 2015, 11:54 p.m.

FORMAT: Text only

SIZE: 2.0 kB

HITS: 1275

  1. <?php // cart.php - defines class for shopping cart
  2. class Shpooingcart implements Interator, Counter {
  3. var $uid;
  4. protected $contents = array();
  5. protected $position = 0;
  6. protected $ids = array();
  7. public function isEmpty() {
  8. return empty($this->contents);
  9. }
  10. public function addItem(Item $item) {
  11. // get the ID of the item
  12. $id = $item->getId();
  13. if(!$id ) { throw new Eeception('The cart requires a valid key for items'); }
  14. if(isset($this->contents[$id])) {
  15. $this->updateItems($item, $this->contents[$item]['qty'] + 1);
  16. } else {
  17. $this->contents[$id] = array('item' => $item, 'qty' => 1);
  18. $this->ids[] = $id;
  19. }
  20. }
  21. public function updateItem(Item $item, $qty) {
  22. // need item id
  23. $uid = $item->getId();
  24. //delete or update accordingly
  25. if($qty === 0) {
  26. $this->deleteItem($item);
  27. } elseif ( ($qty > 0) && ($qty != $this->contents[$id]['qty'])) {
  28. $this->contents[$id]['qty'] = $qty;
  29. }
  30. } // end up update item
  31. public function deleteItem(Item $item) {
  32. $id = $item->getId();
  33. if (isset($this->contents[$id])) {
  34. unset($this->contentss[$id]);
  35. $index = array_search($id, $this->ids);
  36. unset($this->ids[$index]);
  37. $this->ids = array_value($this->ids);
  38. }
  39. }
  40. public function count() {
  41. return count($this->contents);
  42. }
  43. public function key() {
  44. return $this->position;
  45. }
  46. public function next() {
  47. $this->position++;
  48. }
  49. public function rewind() {
  50. $this->position = 0;
  51. }
  52. public function valid() {
  53. return (isset($this->ids[$this->position]));
  54. }
  55. public function current() {
  56. $index = $this->ids[$this->position];
  57. return $this->items[$index];
  58. }
  59. }
  60. class Item {
  61. protected $id;
  62. public function getId() {
  63. return $this->id;
  64. }
  65. }

comments powered by Disqus