>  기사  >  백엔드 개발  >  PHP 모방 장바구니 및 기능 분석

PHP 모방 장바구니 및 기능 분석

墨辰丷
墨辰丷원래의
2018-06-08 10:04:091189검색

이 글은 주로 PHP 모방 장바구니를 소개하고 그 기능을 분석한 것입니다. 관심 있는 친구들이 참고하면 도움이 될 것입니다.

CodeIgniter의 장바구니 클래스가 여기에 모방되었습니다

장바구니의 기본 기능:

1) 장바구니에 항목 추가
2) 장바구니에서 항목 삭제
3) 장바구니 항목 정보 업데이트 [ +1/- 1]
4) 장바구니에 담긴 상품 개수 계산
1. 전체 상품
2. 총 수량
3. 총 금액
5) 개별 쇼핑 상품의 수량 및 금액 계산
6) 장바구니 지우기

php 파일은 다음과 같습니다.

<?php
/**
 *
 * @author quanshuidingdang
 */
class Cart {
 //物品id及名称规则,调试信息控制
 private $product_id_rule = &#39;\.a-z0-9-_&#39;; //小写字母 | 数字 | ._-
 private $product_name_rule = &#39;\.\:a-z0-9-_&#39;;//小写字母 | 数字 | ._-:
 private $debug = TRUE;
 //购物车
 private $_cart_contents = array();
 /**
  * 构造函数
  *
  * @param array
  */
 public function __construct() {
  //是否第一次使用?
  if(isset($_SESSION[&#39;cart_contents&#39;])) {
   $this->_cart_contents = $_SESSION[&#39;cart_contents&#39;];
  } else {
   $this->_cart_contents[&#39;cart_total&#39;] = 0;
   $this->_cart_contents[&#39;total_items&#39;] = 0;
  }
  if($this->debug === TRUE) {
   //$this->_log("cart_create_success");
  }
 }
 /**
  * 将物品加入购物车
  *
  * @access public
  * @param array 一维或多维数组,必须包含键值名: 
      id -> 物品ID标识, 
      qty -> 数量(quantity), 
      price -> 单价(price), 
      name -> 物品姓名
  * @return bool
  */
 public function insert($items = array()) {
  //输入物品参数异常
  if( ! is_array($items) OR count($items) == 0) {
   if($this->debug === TRUE) {
    $this->_log("cart_no_items_insert");
   }
   return FALSE;
  }
  //物品参数处理
  $save_cart = FALSE;
  if(isset($items[&#39;id&#39;])) {
   if($this->_insert($items) === TRUE) {
    $save_cart = TRUE;
   }
  } else {
   foreach($items as $val) {
    if(is_array($val) AND isset($val[&#39;id&#39;])) {
     if($this->_insert($val) == TRUE) {
      $save_cart = TRUE;
     }
    }
   }
  }
  //当插入成功后保存数据到session
  if($save_cart) {
   $this->_save_cart();
   return TRUE;
  }
  return FALSE;
 }
 /**
  * 更新购物车物品信息
  *
  * @access public
  * @param array
  * @return bool
  */
 public function update($items = array()) {
  //输入物品参数异常
  if( !is_array($items) OR count($items) == 0) {
   if($this->debug === TRUE) {
    $this->_log("cart_no_items_insert");
   }
   return FALSE;
  }
  //物品参数处理
  $save_cart = FALSE;
  if(isset($items[&#39;rowid&#39;]) AND isset($items[&#39;qty&#39;])) {
   if($this->_update($items) === TRUE) {
    $save_cart = TRUE;
   }
  } else {
   foreach($items as $val) {
    if(is_array($val) AND isset($val[&#39;rowid&#39;]) AND isset($val[&#39;qty&#39;])) {
     if($this->_update($val) === TRUE) {
      $save_cart = TRUE;
     }
    }
   }
  }
  //当更新成功后保存数据到session
  if($save_cart) {
   $this->_save_cart();
   return TRUE;
  }
  return FALSE;
 }
 /**
  * 获取购物车物品总金额
  *
  * @return int
  */
 public function total() {
  return $this->_cart_contents[&#39;cart_total&#39;];
 }
 /**
  * 获取购物车物品种类
  *
  * @return int
  */
 public function total_items() {
  return $this->_cart_contents[&#39;total_items&#39;];
 }
 /**
  * 获取购物车
  *
  * @return array
  */
 public function contents() {
  return $this->_cart_contents;
 }
 /**
  * 获取购物车物品options
  *
  * @param string
  * @return array
  */
 public function options($rowid = &#39;&#39;) {
  if($this->has_options($rowid)) {
   return $this->_cart_contents[$rowid][&#39;options&#39;];
  } else {
   return array();
  }
 }
 /**
  * 清空购物车
  *
  */
 public function destroy() {
  unset($this->_cart_contents);
  $this->_cart_contents[&#39;cart_total&#39;] = 0;
  $this->_cart_contents[&#39;total_items&#39;] = 0;
  unset($_SESSION[&#39;cart_contents&#39;]);
 }
 /**
  * 判断购物车物品是否有options选项
  * 
  * @param string
  * @return bool
  */
 private function has_options($rowid = &#39;&#39;) {
  if( ! isset($this->_cart_contents[$rowid][&#39;options&#39;]) OR count($this->_cart_contents[$rowid][&#39;options&#39;]) === 0) {
   return FALSE;
  }
  return TRUE;
 }
 /**
  * 插入数据
  *
  * @access private 
  * @param array
  * @return bool
  */
 private function _insert($items = array()) {
  //输入物品参数异常
  if( ! is_array($items) OR count($items) == 0) {
   if($this->debug === TRUE) {
    $this->_log("cart_no_data_insert");
   }
   return FALSE;
  }
  //如果物品参数无效(无id/qty/price/name)
  if( ! isset($items[&#39;id&#39;]) OR ! isset($items[&#39;qty&#39;]) OR ! isset($items[&#39;price&#39;]) OR ! isset($items[&#39;name&#39;])) {
   if($this->debug === TRUE) {
    $this->_log("cart_items_data_invalid");
   }
   return FALSE;
  }
  //去除物品数量左零及非数字字符
  $items[&#39;qty&#39;] = trim(preg_replace(&#39;/([^0-9])/i&#39;, &#39;&#39;, $items[&#39;qty&#39;]));
  $items[&#39;qty&#39;] = trim(preg_replace(&#39;/^([0]+)/i&#39;, &#39;&#39;, $items[&#39;qty&#39;]));
  //如果物品数量为0,或非数字,则我们对购物车不做任何处理!
  if( ! is_numeric($items[&#39;qty&#39;]) OR $items[&#39;qty&#39;] == 0) {
   if($this->debug === TRUE) {
    $this->_log("cart_items_data(qty)_invalid");
   }
   return FALSE;
  }
  //物品ID正则判断
  if( ! preg_match(&#39;/^[&#39;.$this->product_id_rule.&#39;]+$/i&#39;, $items[&#39;id&#39;])) {
   if($this->debug === TRUE) {
    $this->_log("cart_items_data(id)_invalid");
   }
   return FALSE;
  }
  //物品名称正则判断
  if( ! preg_match(&#39;/^[&#39;.$this->product_name_rule.&#39;]+$/i&#39;, $items[&#39;name&#39;])) {
   if($this->debug === TRUE) {
    $this->_log("cart_items_data(name)_invalid");
   }
   return FALSE;
  }
  //去除物品单价左零及非数字(带小数点)字符
  $items[&#39;price&#39;] = trim(preg_replace(&#39;/([^0-9\.])/i&#39;, &#39;&#39;, $items[&#39;price&#39;]));
  $items[&#39;price&#39;] = trim(preg_replace(&#39;/^([0]+)/i&#39;, &#39;&#39;, $items[&#39;price&#39;]));
  //如果物品单价非数字
  if( ! is_numeric($items[&#39;price&#39;])) {
   if($this->debug === TRUE) {
    $this->_log("cart_items_data(price)_invalid");
   }
   return FALSE;
  }
  //生成物品的唯一id
  if(isset($items[&#39;options&#39;]) AND count($items[&#39;options&#39;]) >0) {
   $rowid = md5($items[&#39;id&#39;].implode(&#39;&#39;, $items[&#39;options&#39;]));
  } else {
   $rowid = md5($items[&#39;id&#39;]);
  }
  //加入物品到购物车
  unset($this->_cart_contents[$rowid]);
  $this->_cart_contents[$rowid][&#39;rowid&#39;] = $rowid;
  foreach($items as $key => $val) {
   $this->_cart_contents[$rowid][$key] = $val;
  }
  return TRUE;
 }
 /**
  * 更新购物车物品信息(私有)
  *
  * @access private
  * @param array
  * @return bool
  */
 private function _update($items = array()) {
  //输入物品参数异常
  if( ! isset($items[&#39;rowid&#39;]) OR ! isset($items[&#39;qty&#39;]) OR ! isset($this->_cart_contents[$items[&#39;rowid&#39;]])) {
   if($this->debug == TRUE) {
    $this->_log("cart_items_data_invalid");
   }
   return FALSE;
  }
  //去除物品数量左零及非数字字符
  $items[&#39;qty&#39;] = preg_replace(&#39;/([^0-9])/i&#39;, &#39;&#39;, $items[&#39;qty&#39;]);
  $items[&#39;qty&#39;] = preg_replace(&#39;/^([0]+)/i&#39;, &#39;&#39;, $items[&#39;qty&#39;]);
  //如果物品数量非数字,对购物车不做任何处理!
  if( ! is_numeric($items[&#39;qty&#39;])) {
   if($this->debug === TRUE) {
    $this->_log("cart_items_data(qty)_invalid");
   }
   return FALSE;
  }
  //如果购物车物品数量与需要更新的物品数量一致,则不需要更新
  if($this->_cart_contents[$items[&#39;rowid&#39;]][&#39;qty&#39;] == $items[&#39;qty&#39;]) {
   if($this->debug === TRUE) {
    $this->_log("cart_items_data(qty)_equal");
   }
   return FALSE;
  }
  //如果需要更新的物品数量等于0,表示不需要这件物品,从购物车种清除
  //否则修改购物车物品数量等于输入的物品数量
  if($items[&#39;qty&#39;] == 0) {
   unset($this->_cart_contents[$items[&#39;rowid&#39;]]);
  } else {
   $this->_cart_contents[$items[&#39;rowid&#39;]][&#39;qty&#39;] = $items[&#39;qty&#39;];
  }
  return TRUE;
 }
 /**
  * 保存购物车数据到session
  * 
  * @access private
  * @return bool
  */
 private function _save_cart() {
  //首先清除购物车总物品种类及总金额
  unset($this->_cart_contents[&#39;total_items&#39;]);
  unset($this->_cart_contents[&#39;cart_total&#39;]);
  //然后遍历数组统计物品种类及总金额
  $total = 0;
  foreach($this->_cart_contents as $key => $val) {
   if( ! is_array($val) OR ! isset($val[&#39;price&#39;]) OR ! isset($val[&#39;qty&#39;])) {
    continue;
   }
   $total += ($val[&#39;price&#39;] * $val[&#39;qty&#39;]);
   //每种物品的总金额
   $this->_cart_contents[$key][&#39;subtotal&#39;] = ($val[&#39;price&#39;] * $val[&#39;qty&#39;]);
  }
  //设置购物车总物品种类及总金额
  $this->_cart_contents[&#39;total_items&#39;] = count($this->_cart_contents);
  $this->_cart_contents[&#39;cart_total&#39;] = $total;
  //如果购物车的元素个数少于等于2,说明购物车为空
  if(count($this->_cart_contents) <= 2) {
   unset($_SESSION[&#39;cart_contents&#39;]);
   return FALSE;
  }
  //保存购物车数据到session
  $_SESSION[&#39;cart_contents&#39;] = $this->_cart_contents;
  return TRUE;
 }
 /**
  * 日志记录
  *
  * @access private
  * @param string
  * @return bool
  */
 private function _log($msg) {
  return @file_put_contents(&#39;cart_err.log&#39;, $msg, FILE_APPEND);
 }
}
/*End of file cart.php*/
/*Location /htdocs/cart.php*/

cart_demo.php 파일은 다음과 같습니다.

<?php
session_start();
require_once(&#39;cart.php&#39;);
$items = array(
   0 => array(
   &#39;id&#39; => &#39;sp001&#39;,
   &#39;qty&#39; => 20,
   &#39;price&#39; => &#39;10.50&#39;,
   &#39;name&#39; => &#39;a002&#39;,
   &#39;options&#39; => array(
       &#39;made&#39; => &#39;china&#39;,
       &#39;company&#39; => &#39;bgi&#39;
       )
   ),
   1 => array(
   &#39;id&#39; => &#39;sp002&#39;,
   &#39;qty&#39; => 1,
   &#39;price&#39; => &#39;3.50&#39;,
   &#39;name&#39; => &#39;b002&#39;
   )
  );
$arr = array(
   &#39;rowid&#39; => &#39;86dbb7cb58a667558b4bbb1f60330028&#39;,
   &#39;qty&#39; => 21
  );
$cart = new Cart();
$cart->insert($items);
//var_dump($cart->contents());
$cart->update($arr);
var_dump($cart->contents());
//$cart->destroy();
//var_dump($_SESSION[&#39;cart_contents&#39;]);
/*end of php*/

요약: 위 내용은 이 글의 전체 내용입니다. 모두의 공부.

관련 권장 사항:

PHP로 파일을 재귀적으로 작동하는 방법

세션과 결합된 PHP로 데이터베이스를 작동하는 방법

PHP로 원격 이미지를 현지화하는 방법

위 내용은 PHP 모방 장바구니 및 기능 분석의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.