php实现仿写CodeIgniter的购物车类


Posted in PHP onJuly 29, 2015

本文实例讲述了php实现仿写CodeIgniter的购物车类。分享给大家供大家参考。具体如下:

这里仿写CodeIgniter的购物车类

购物车基本功能:

1) 将物品加入购物车
2) 从购物车中删除物品
3) 更新购物车物品信息 【+1/-1】
4) 对购物车物品进行统计
   1. 总项目
   2. 总数量
   3. 总金额
5) 对购物单项物品的数量及金额进行统计
6) 清空购物车

cart.php文件如下:



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

cart_demo.php文件如下:

<?php
session_start();
require_once('cart.php');
$items = array(
   0 => array(
   'id' => 'sp001',
   'qty' => 20,
   'price' => '10.50',
   'name' => 'a002',
   'options' => array(
       'made' => 'china',
       'company' => 'bgi'
       )
   ),
   1 => array(
   'id' => 'sp002',
   'qty' => 1,
   'price' => '3.50',
   'name' => 'b002'
   )
  );
$arr = array(
   'rowid' => '86dbb7cb58a667558b4bbb1f60330028',
   'qty' => 21
  );
$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*/

希望本文所述对大家的php程序设计有所帮助。

PHP 相关文章推荐
如何使用PHP中的字符串函数
Nov 24 PHP
php学习笔记 php中面向对象三大特性之一[封装性]的应用
Jun 13 PHP
解析PHP对现有搜索引擎的调用
Jun 25 PHP
php安装xdebug/php安装pear/phpunit详解步骤(图)
Dec 22 PHP
CI框架开发新浪微博登录接口源码完整版
May 28 PHP
php实现根据url自动生成缩略图的方法
Sep 23 PHP
php通过array_push()函数添加多个变量到数组末尾的方法
Mar 18 PHP
PHP文件操作方法汇总
Jul 01 PHP
PHP中两个float(浮点数)比较实例分析
Sep 27 PHP
Yii CGridView用法实例详解
Jul 12 PHP
支付宝支付开发――当面付条码支付和扫码支付实例
Nov 04 PHP
Laravel5中Cookie的使用详解
May 03 PHP
PHP使用逆波兰式计算工资的方法
Jul 29 #PHP
ThinkPHP实现递归无级分类――代码少
Jul 29 #PHP
PHP之正则表达式捕获组与非捕获组(详解)
Jul 29 #PHP
PHP实现的简单缓存类
Jul 29 #PHP
PHP实现简单爬虫的方法
Jul 29 #PHP
php获取网站百度快照日期的方法
Jul 29 #PHP
如何通过Linux命令行使用和运行PHP脚本
Jul 29 #PHP
You might like
mysql_fetch_row,mysql_fetch_array,mysql_fetch_assoc的区别
2009/04/24 PHP
php 变量未定义等错误的解决方法
2011/01/12 PHP
php代码运行时间查看类代码分享
2011/08/06 PHP
ThinkPHP提示错误Fatal error: Allowed memory size的解决方法
2015/02/12 PHP
PHP中判断文件存在使用is_file还是file_exists?
2015/04/03 PHP
PHP list() 将数组中的值赋给变量的简单实例
2016/06/13 PHP
Mootools 1.2教程 定时器和哈希简介
2009/09/15 Javascript
Span元素的width属性无效果原因及解决方案
2010/01/15 Javascript
jQuery选择器全面总结
2014/01/06 Javascript
js常用自定义公共函数汇总
2014/01/15 Javascript
基于jquery的simpleValidate简易验证插件
2014/01/31 Javascript
js统计录入文本框中字符的个数并加以限制不超过多少
2014/05/23 Javascript
js使用for循环与innerHTML获取选中tr下td值
2014/09/26 Javascript
angularJS 中$attrs方法使用指南
2015/02/09 Javascript
JavaScript禁止用户多次提交的两种方法
2016/07/24 Javascript
浅谈JavaScript 中有关时间对象的方法
2016/08/15 Javascript
Vuex2.0+Vue2.0构建备忘录应用实践
2016/11/30 Javascript
JavaScript实现替换字符串中最后一个字符的方法
2017/03/07 Javascript
JavaScript对象的特性与实践应用深入详解
2018/12/30 Javascript
node.js事件轮询机制原理知识点
2019/12/22 Javascript
基于Vue2实现移动端图片上传、压缩、拖拽排序、拖拽删除功能
2021/01/05 Vue.js
python实现井字棋游戏
2020/03/30 Python
Python中的id()函数指的什么
2017/10/17 Python
python简单图片操作:打开\显示\保存图像方法介绍
2017/11/23 Python
Apache,wsgi,django 程序部署配置方法详解
2019/07/01 Python
pytorch 改变tensor尺寸的实现
2020/01/03 Python
Python预测2020高考分数和录取情况
2020/07/08 Python
基于canvas使用贝塞尔曲线平滑拟合折线段的方法
2018/01/10 HTML / CSS
Scotch Porter官方网站:男士美容产品
2020/08/31 全球购物
C/C++ 笔试、面试题目大汇总
2015/11/21 面试题
物流管理毕业生自荐信
2013/10/24 职场文书
计算机求职自荐信范文
2014/04/19 职场文书
四风问题对照检查材料思想汇报
2014/10/07 职场文书
详解JS WebSocket断开原因和心跳机制
2021/05/07 Javascript
中国古风插画师排行榜:夏达第一,第三是阴阳师姑获鸟皮肤创作者
2022/03/18 国漫
win10截图快捷键win+shift+s没有反应无法截图怎么解决?
2022/08/14 数码科技