The _php skill of the shopping cart class that implements the imitation writing CodeIgniter in PHP

Source: Internet
Author: User
Tags foreach numeric lowercase md5 trim unique id codeigniter

This article describes the implementation of PHP CodeIgniter shopping cart class. Share to everyone for your reference. as follows:

This is a CodeIgniter shopping cart class.

Shopping Cart basic function:

1 Add items to the shopping cart
2 Remove items from the shopping cart
3 Update Shopping Cart items Information "+1/-1"
4 The shopping cart items for statistics
1. General Projects
2. Total Quantity
3. Total Amount
5 The number of items and the amount of shopping item statistics
6) Empty the shopping cart

cart.php files are as follows:



<?php/** * * @author Quanshuidingdang/class Cart {//item ID and name rules, debug information control private $product _id_rule = ' \.a-z0-9-_ ' ; Lowercase Letter | number |. _-private $product _name_rule = ' \.\:a-z0-9-_ ';//lowercase Letter |
 number |. _-: Private $debug = TRUE;
 Shopping cart Private $_cart_contents = array ();
  /** * Constructor * * @param array/Public function __construct () {//Is it used for the first time?
  if (Isset ($_session[' cart_contents ')) {$this->_cart_contents = $_session[' cart_contents '];
   else {$this->_cart_contents[' cart_total '] = 0;
  $this->_cart_contents[' total_items '] = 0;
  } if ($this->debug = = TRUE) {//$this->_log ("cart_create_success"); }/** * Add items to Cart * * @access public * @param array one-dimensional or multidimensional array, must contain the key value name: ID-> item ID identification, QTY-> number Quantity (quantity), price-> (prices), name-> item names * @return BOOL/Public Function Insert ($items = a
 Rray ()) {//input item parameter exception if (! Is_array ($items) OR count ($items) = = 0) {if ($this->debug = = TRUE) {   $this->_log ("Cart_no_items_insert");
  return FALSE;
  }//Item parameter processing $save _cart = FALSE;
   if (Isset ($items [' id])) {if ($this->_insert ($items) = = True) {$save _cart = true; } else {foreach ($items as $val) {if (Is_array ($val) and Isset ($val [' ID '])) {if ($this->_insert ($val) =
     = True) {$save _cart = true;
   Save the data to session if ($save _cart) {$this->_save_cart () when the insert succeeds;
  return TRUE;
 return FALSE; /** * Update Shopping cart Article information * @access public * @param array * @return BOOL/Public Function update ($items = Array ( ) {//input item parameter exception if (!is_array ($items) OR count ($items) = = 0) {if ($this->debug = = TRUE) {$this->_log ("C
   Art_no_items_insert ");
  return FALSE;
  }//Item parameter processing $save _cart = FALSE;
   if (Isset ($items [' rowID ']) and isset ($items [' qty '])) {if ($this->_update ($items) = = True) {$save _cart = true; } else {foreach ($items as $val) {if (Is_array ($val) and Isset ($val [' rowID ']) and isset ($val [' qty '])) {if ($this->_update ($val) = = True) {$save _cart = true;
   Save data to session if ($save _cart) {$this->_save_cart () when the update succeeds;
  return TRUE;
 return FALSE; 
 /** * Get the total amount of shopping cart items * * @return int */Public function sum () {return $this->_cart_contents[' cart_total '); /** * Get CART Item type * * @return int */Public Function Total_items () {return $this->_cart_contents[' Total_
 Items '];
 /** * Get cart * * @return Array */Public function contents () {return $this->_cart_contents; /** * Get Shopping cart items Options * * @param string * @return Array/Public function options ($rowid = ') {if ($this-
  >has_options ($rowid)) {return $this->_cart_contents[$rowid [' Options '];
  else {return array ();
  }/** * Empty shopping cart */Public function destroy () {unset ($this->_cart_contents);
  $this->_cart_contents[' cart_total '] = 0; $this->_cart_contents[' total_items '] = 0;
 unset ($_session[' cart_contents '));
  /** * Determine if shopping cart items have options * * @param string * @return bool/Private Function has_options ($rowid = ') { if (! isset ($this->_cart_contents[$rowid] [' Options ']) OR count ($this->_cart_contents[$rowid] [' options ']) = = 0
  ) {return FALSE;
 return TRUE; /** * Insert Data * * @access private * @param array * @return BOOL/Private Function _insert ($items = Array () {//input item parameter exception if (! Is_array ($items) OR count ($items) = = 0) {if ($this->debug = = TRUE) {$this->_log ("C
   Art_no_data_insert ");
  return FALSE; //If the item parameter is invalid (no id/qty/price/name) if (! isset ($items [' id ']) or! isset ($items [' qty ']) or! isset ($items [' price ']) or!
   Isset ($items [' name ']) {if ($this->debug = = TRUE) {$this->_log ("Cart_items_data_invalid");
  return FALSE;
  //Remove Item quantity left 0 and non-numeric character $items [' qty '] = Trim (preg_replace ('/[[^0-9])/I ', ', $items [' qty '])); $items [' QTY '] = Trim (Preg_replace ('/^ ([0]+)/I ', ', $items [' qty ']));
  If the item quantity is 0, or not the number, then we do not have to do any processing to the shopping cart! if (! is_numeric ($items [' qty ']) OR $items [' qty '] = = 0) {if ($this->debug = = TRUE) {$this->_log ("Cart_items_
   Data (Qty) _invalid ");
  return FALSE; }//item ID is judged if (! Preg_match ('/^['. $this->product_id_rule. ')
   +$/i ', $items [' id ']) {if ($this->debug = = TRUE) {$this->_log ("Cart_items_data (ID) _invalid");
  return FALSE; }//Item name is judged if (! Preg_match ('/^['. $this->product_name_rule. ')
   +$/i ', $items [' name ']) {if ($this->debug = = TRUE) {$this->_log ("Cart_items_data (name) _invalid");
  return FALSE; //Remove Item unit price left 0 and Non-numeric (with decimal points) character $items [' prices '] = Trim (Preg_replace ('/([^0-9\.])
  /I ', ', $items [' Price ']]);
  $items [' price '] = Trim (Preg_replace ('/^ ([0]+)/I ', ', $items [' Price ']); If the item unit price is not a digital if (! is_numeric ($items [' prices ']) {if ($this->debug = = TRUE) {$this->_log ("Cart_items_data" p
   Rice) _invalid "); } RETurn FALSE; }//Generate unique ID if (isset ($items [' Options ']) and count ($items [' Options ']) >0 {$rowid = MD5 ($items [' ID '].implode ('
  ', $items [' Options ']]);
  else {$rowid = MD5 ($items [' id ']);
  //Add Items to Cart unset ($this->_cart_contents[$rowid]);
  $this->_cart_contents[$rowid] [' rowid '] = $rowid;
  foreach ($items as $key => $val) {$this->_cart_contents[$rowid] [$key] = $val;
 return TRUE;  /** * Update Shopping Cart article information (private) * @access private * @param array * @return BOOL/Private Function _update ($items = Array ()) {//input item parameter exception if (! isset ($items [' rowid ']) or! isset ($items [' qty ']) or! isset ($this->_cart_contents[$ite
   ms[' rowID '])) {if ($this->debug = = TRUE) {$this->_log ("Cart_items_data_invalid");
  return FALSE;
  //Remove items quantity left 0 and non-numeric characters $items [' qty '] = preg_replace ('/[[^0-9])/I ', ', $items [' qty ']);
  $items [' qty '] = preg_replace ('/^ ([0]+)/I ', ', $items [' qty ']);
  If the number of items is not digital, do not do any processing on the shopping cart! if (! is_numeric ($items [' qty ']) {if ($this->debug = = TRUE) {$this->_log ("Cart_items_data (qty) _invalid");
  return FALSE; //If the number of shopping cart items is consistent with the number of items that need to be updated, you do not need to update if ($this->_cart_contents[$items [' rowID ']][' qty '] = = $items [' qty ']) {if ($this-&
   Gt;debug = = TRUE) {$this->_log ("Cart_items_data (qty) _equal");
  return FALSE; //If you need to update the number of items equal to 0, indicating that you do not need this item, from the shopping cart type to clear/or modify the number of shopping cart items equal to the number of items entered if ($items [' qty '] = = 0) {unset ($this->_cart_conten
  ts[$items [' rowID ']]);
  else {$this->_cart_contents[$items [' rowID ']][' qty '] = $items [' qty '];
 return TRUE; /** * Save CART data to session * * @access private * @return bool/Private Function _save_cart () {///First clear cart total item species
  Class and Total amount unset ($this->_cart_contents[' total_items '));
  unset ($this->_cart_contents[' cart_total ']);
  Then iterate over the array of categories of items and the total amount $total = 0; foreach ($this->_cart_contents as $key => $val) {if (! Is_array ($val) or! isset ($val [' price ']) or! isset ($val ['
   Qty ']) {continue; } $total + + ($val [' Price '] * $val [' qty ']);
  The total amount of each item $this->_cart_contents[$key] [' subtotal '] = ($val [' Price '] * $val [' qty ']);
  //Set the total item type and total amount of the cart $this->_cart_contents[' total_items '] = count ($this->_cart_contents);
  $this->_cart_contents[' cart_total '] = $total;
   If the number of elements in the shopping cart is less than 2, the shopping cart is empty if (count ($this->_cart_contents) <= 2) {unset ($_session[' cart_contents '));
  return FALSE;
  //Save CART Data to session $_session[' cart_contents ' = $this->_cart_contents;
 return TRUE; /** * Log Record * @access private * @param string * @return bool/Private Function _log ($msg) {return @f
 Ile_put_contents (' Cart_err.log ', $msg, file_append);
 }/*end of File cart.php*//*location/htdocs/cart.php*/

cart_demo.php files are as follows:

<?php
session_start ();
Require_once (' cart.php ');
$items = Array (
   0 => Array (
   ' id ' => ' sp001 ',
   ' qty ' =>, ' price ' => ' 10.50 '
   , '
   name ' => ; ' a002 ',
   ' options ' => array (
       ' made ' => ', ' Company ' => ' BGI '
       )
   ),
   1 => Array (
   ' id ' => ' sp002 ', '
   qty ' => 1,
   ' price ' => ' 3.50 ',
   ' name ' => ' b002 '
   )
  );
$arr = Array (
   ' rowid ' => ' 86dbb7cb58a667558b4bbb1f60330028 ', '
   qty ' =>
  );
$cart = new cart ();
$cart->insert ($items);
Var_dump ($cart->contents ());
$cart->update ($arr);
Var_dump ($cart->contents ());
$cart->destroy ();
Var_dump ($_session[' cart_contents '));
/*end of php*/

I hope this article will help you with your PHP program design.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.