8.3. Code and Code Explanation

I will first discuss writing the ShoppingCart class as it is used by the storefront files. Then I will discuss the two front-end files, shop.php and cart.php. Finally, I will cover the administrative files, which you will use to populate the inventory database with entries.

8.3.1. The ShoppingCart Class

The first component I will present is the ShoppingCart class. The class will be responsible for maintaining the list of items shoppers have selected until they are ready to check out. Essentially this list is an array, but various methods and properties will be made available to make working with the list easier. Table 8-1 shows the properties ShoppingCart will expose and Table 8-2 shows the methods.

Table 8-1. ShoppingCart Properties
PropertyDescription
contentsReturns the entire contents of the cart as an array
isEmptyReturns Boolean whether or not the cart is empty
totalItemsReturns the total number of distinct items in the cart
totalQtyReturns the total quantity of items in the cart
Table 8-2. ShoppingCart Methods
MethodDescription
construct()Initializes a new ShoppingCart object
addItem(item[, qty])Adds an item to the shopping cart
qtyItem(item)Returns the quantity of an item in the cart
removeItem(item)Removes an item from the shopping cart
removeAll()Empties the contents of the shopping cart

The class will need one private property to store the list of products which will be initialized to a blank array in the constructor. The array will later store ...

Get PHP and MySQL®: Create-Modify-Reuse now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.