Prev | Current Page 474 | Next

Emilian Balanescu and Cristian Darie

"Beginning PHP and MySQL E-Commerce: From Novice to Professional, Second Edition"

Include a reference to shopping_cart.php in index.php:
// Load Business Tier
require_once BUSINESS_DIR . 'catalog.php';
require_once BUSINESS_DIR . 'shopping_cart.php';
How It Works: The Business Tier of the Shopping Cart
When a visitor adds a product or requests any shopping cart operation, we generate a shopping cart ID for the visitor
if there isn??™t one. You take care of this in the SetCartId() method that generates a cart ID to the $_mCartId member
of the ShoppingCart class. The shopping cart ID is also saved in the visitor??™s session and in a persistent cookie.
SetCartId() starts by verifying that the $_mCartId member was already set, in which case we don??™t need to
read it from external sources:
public static function SetCartId()
{
// If the cart ID hasn't already been set ...
if (self::$_mCartId == '')
{
If we don??™t have the ID in the member variable, the next place to look is the visitor??™s session:
// If the visitor's cart ID is in the session, get it from there
if (isset ($_SESSION['cart_id']))
{
self::$_mCartId = $_SESSION['cart_id'];
}
If the ID couldn??™t be found in the session either, we check whether it was saved as a cookie. If yes, we save the
value both to the session and to the $_mCartId member, and we regenerate the cookie to reset its expiration date:
// If not, check whether the cart ID was saved as a cookie
elseif (isset ($_COOKIE['cart_id']))
{
// Save the cart ID from the cookie
CHAPTER 12 ?–  CREATING YOUR OWN SHOPPING CART 376
self::$_mCartId = $_COOKIE['cart_id'];
$_SESSION['cart_id'] = self::$_mCartId;
// Regenerate cookie to be valid for 7 days (604800 seconds)
setcookie('cart_id', self::$_mCartId, time() + 604800);
}
Finally, if the cart ID can??™t be found anywhere, a new one is generated and saved to the session, to the $_mCartId
member, and to the persistent cookie:
else
{
/* Generate cart id and save it to the $_mCartId class member,
the session and a cookie (on subsequent requests $_mCartId
will be populated from the session) */
self::$_mCartId = md5(uniqid(rand(), true));
// Store cart id in session
$_SESSION['cart_id'] = self::$_mCartId;
// Cookie will be valid for 7 days (604800 seconds)
setcookie('cart_id', self::$_mCartId, time() + 604800);
}
}
}
Three functions are used to generate the cart ID: md5(), uniqid(), and rand().


Pages:
462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486
www.books61.hobbitstory.com tanie noclegi międzyzdroje pokoje windsurfing Władysławowo noclegi e-lady