Using the Code
As is often the case with OOP, all of the hard work and thought goes into designing and defining the classes; using them becomes really straightforward.
To use this code, you would start by creating a shopping cart object:
$cart = new ShoppingCart();
The cart could easily be stored in the session or retrieved from it, to maintain state throughout the user’s session:
if (isset($_SESSION['cart'])) { $cart = $_SESSION['cart']; } else { $cart = new ShoppingCart(); }
Next, you’d create an Item object for each item to be added to the cart:
$w1 = new Item('W139', 'Some Widget', 23.45); $w2 = new Item('W384', 'Another Widget', 12.39); $w3 = new Item('W55', 'Cheap Widget', 5.00);
(Presumably, all of these actions would take place over the course of several pages. They’ve been combined here for demonstration purposes.)
Now, you can add, update, and delete items:
$cart->addItem($w1); $cart->addItem($w2); $cart->addItem($w3); $cart->updateItem($w2, 4); $cart->updateItem($w1, 1); $cart->deleteItem($w3);
Because the $cart class throws exceptions, you can wrap all this in a try...catch block and then properly handle the exceptions.
Finally, to show the cart’s contents, use a loop:
echo '<h2>Cart Contents (' . count($cart) . ' items)</h2>'; if (!$cart->isEmpty()) { foreach ($cart as $arr) { $item = $arr['item']; printf('<p><strong>%s</strong>: %d @ $%0.2f each.<p>', $item->getName(), $arr['qty'], $item->getPrice()); } // End of foreach loop! } // End of IF.
Figure 2 A simple output of the cart’s contents.
For each item in the cart, the loop will return an array. This array has two elements: the Item object indexed at item and the quantity of that item indexed at qty. As the Item object itself is being stored, once it’s retrieved you can use its getName() and getPrice() methods accordingly (or whatever methods you’ve defined in your class). For simplicity sake in this example, the output is created within some HTML paragraphs, and the printf() method is called to do this.