PHP Imitation shopping cart and analysis of its functions

Source: Internet
Author: User
This article mainly introduces the PHP imitation writing shopping cart and analysis of its functions, interested in the reference of friends, I hope to help you.

Here is the imitation of codeigniter shopping cart class

Shopping Cart Basic Features:

1) Add items to your shopping cart
2) remove items from your shopping cart
3) Update Shopping cart item Information "+1/-1"
4) Statistics on shopping cart items
1. Total Items
2. Total Quantity
3. Total Amount
5) Statistics on the quantity and amount of items in the shopping item
6) Empty Cart

The cart.php file is as follows:

<?php/** * * @author Quanshuidingdang */class Cart {//item ID and name rules, debug information control private $product _id_rule = ' \.a-z0-9-_ ';//lowercase letters | number |. _-private $product _name_rule = ' \.\:a-z0-9-_ ';//Small Letter | number |. _-: Private $debug = TRUE; Shopping cart Private $_cart_contents = array ();  /** * Constructor * * @param array */Public function __construct () {//Are you using it 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 arrays, must contain key-value names: ID-and item ID ID, number of qty (quanti ty), price, item name * @return BOOL */Public Function Insert ($items = Array ()) {// Enter the item parameter exception if (! Is_array ($items) OR count ($items) = = 0) {if ($this->debug = = = TRUE) {$this->_log ("Cart_no_item   S_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) = = TR     UE) {$save _cart = TRUE;   }}}}//When the insert is successful, save the data to the session if ($save _cart) {$this->_save_cart ();  return TRUE; } return FALSE; }/** * Update shopping Cart Item Information * * @access public * @param array * @return BOOL */Public Function update ($items = Array ()) {// Enter the 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 [' 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 ($th Is->_update ($val) = = = TRUE) {      $save _cart = TRUE;   }}}}//When the update is successful, save the data to the session if ($save _cart) {$this->_save_cart ();  return TRUE; } return FALSE;  }/** * Get the total amount of shopping cart items * * @return int */Public Function totals () {return $this->_cart_contents[' cart_total ');}/**  * Get Shopping 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)) {retur  n $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 ()) {//output Enter Item parameter exception if (! Is_array ($items) OR count ($items) = = 0) {if ($this->debug = = = TRUE) {$this->_log ("Cart_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! is   Set ($items [' name '])) {if ($this->debug = = = TRUE) {$this->_log ("Cart_items_data_invalid");  } return FALSE;  }//Remove the number of items left 0 and non-numeric characters $items [' qty '] = Trim (Preg_replace ('/([^0-9])/I ', ', $items [' qty ']);  $items [' qty '] = Trim (Preg_replace ('/^ ([0]+)/I ', ' ', $items [' qty ']);  If the number of items is 0, or not the number, then we do not do any processing of 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; }//The 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; }//The 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) characters $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 non-numeric if (! is_numeric ($items [price])) {if ($this->debug = = = TRUE) {$this->_log ("Cart_items_data (pric   e) _invalid ");  } return FALSE; }//Generate an item's 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 cart item 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[$items [' rowID '   ]]) {if ($this->debug = = TRUE) {$this->_log ("Cart_items_data_invalid");  } return FALSE;  }//Remove the number of items 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 items in the shopping cart is the same as the number of items that need to be updated, you do not need to update the 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, remove from the shopping cart//Otherwise modify the shopping cart item quantity equals the number of items entered if ($items [' qty '] = = 0) {unset ($this->_cart_contents[$  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 Shopping cart Total item type and total amount u  Nset ($this->_cart_contents[' total_items ');  unset ($this->_cart_contents[' cart_total ');  Then iterate over the array statistic item type and total amount $total = 0; foreach ($this->_cart_contents as $key = + $val) {if (! Is_array ($val) or! isset ($val [' price ']) or! isset ($val [' Q   Ty '])) {continue;   } $total + = ($val [' Price '] * $val [' qty '];  The total amount of each item $this->_cart_contents[$key] [' subtotal '] = ($val [' Price '] * $val [' qty ']);  }//Set CART Total item type and total amount $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 or equal to 2,The 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 @file_put_c Ontents (' Cart_err.log ', $msg, file_append); }}/*end of File cart.php*//*location/htdocs/cart.php*/

The cart_demo.php file is as follows:

<?phpsession_start (); require_once (' cart.php '); $items = Array (   0 = = Array (   ' id ' = ' sp001 ',   ' Qty ' = ' + ',   ' price ' = ' 10.50 ',   ' name ' = ' a002 ', ' options '-' + '   Array (       ' made ' = ' China ', c8/> ' 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*/

Summary : The above is the entire content of this article, I hope to be able to help you learn.

Related recommendations:

Php method for recursive operation of files

The method of PHP combined with session operation database

How PHP will localize remote images

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.