php,
which contains the ShoppingCart class. This class has the following methods:
??? SetCartId() generates a new shopping cart ID and saves it on the visitor??™s browser as
a cookie and in the session.
??? GetCartId() returns the shopping cart ID.
??? AddProduct() adds a new product to the visitor??™s shopping cart.
??? Update() modifies a product quantity in the visitor??™s shopping cart or deletes the product
from the cart if the quantity is zero or negative.
??? RemoveProduct() removes a product from the shopping cart.
??? GetCartProducts() retrieves all the products in the shopping cart.
??? GetTotalAmount() returns the total amount of the products in the cart.
??? SaveProductForLater() saves a product in the cart for later.
??? MoveProductToCart() moves a product from the ???Save for later??? list back to the ???main???
shopping cart.
Let??™s write the code.
Exercise: Implementing the Shopping Cart Business Logic
1. First, add the following two lines at the end of your include/config.php file. These constants are used
to differentiate between current shopping cart items and items that are saved for later.
// Shopping cart item types
define('GET_CART_PRODUCTS', 1);
define('GET_CART_SAVED_PRODUCTS', 2);
2. Create a new file called shopping_cart.php in the business folder. Add the following code to the file,
and then we??™ll comment on it afterward:
// Business tier class for the shopping cart
class ShoppingCart
{
// Stores the visitor's Cart ID
private static $_mCartId;
// Private constructor to prevent direct creation of object
private function __construct()
{
}
CHAPTER 12 ?– CREATING YOUR OWN SHOPPING CART 372
/* This will be called by GetCartId to ensure we have the
visitor's cart ID in the visitor's session in case
$_mCartID has no value set */
public static function SetCartId()
{
// If the cart ID hasn't already been set .
Pages:
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483