Creating a Shopping Cart Class
For the second "real-world" use of object-oriented programming, I want to implement as a class the shopping cart system created in Chapter 5, "E-Commerce Techniques." If you look back at cart.php (Script 5.7), you'll see that the one page does several things:
♦ Updates the quantities in the cart
♦ Removes items from the cart (when the user enters a quantity of 0)
♦ Displays the shopping cart in an HTML form
In an object-oriented structure, this can be implemented in many ways. You could start with an abstract ShoppingCart class that is then extended by a more specific WidgetShoppingCart class. I'm going to keep this simple and just go with the WidgetShoppingCart, but check out the Shape and Triangle classes in Chapter 7 for how an inherited abstract class would work.
For this class, each of the preceding features can be turned into a method. Only one attribute, which will store an array of items in the cart, will be required. Unlike the session variable in Chapter 5, which only stored the product IDs and their respective quantities, this cart will store everything about each product: ID, name, color, size, quantity, and price.
Post a comment