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 相关文章推荐
使用TinyButStrong模板引擎来做WEB开发
Mar 16 PHP
解析thinkphp的左右值无限分类
Jun 20 PHP
php中AES加密解密的例子小结
Feb 18 PHP
微信公众平台之快递查询功能用法实例
Apr 14 PHP
PHP+Mysql+jQuery实现发布微博程序 php篇
Oct 15 PHP
php文件上传类完整实例
May 14 PHP
PHP页面跳转实现延时跳转的方法
Dec 10 PHP
PHP实现的贪婪算法实例
Oct 17 PHP
PHPTree――php快速生成无限级分类
Mar 30 PHP
PHP设计模式之适配器模式原理与用法分析
Apr 25 PHP
PHP单例模式模拟Java Bean实现方法示例
Dec 07 PHP
TP5框架实现上传多张图片的方法分析
Mar 29 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
做一个有下拉功能的留言版
2006/10/09 PHP
php inc文件使用的风险和注意事项
2013/11/12 PHP
JavaScript/jQuery 表单美化插件小结
2012/02/14 Javascript
提高jQuery性能的十个诀窍
2013/11/14 Javascript
iframe中子父类窗口调用JS的方法及注意事项
2015/08/25 Javascript
微信小程序 前端源码逻辑和工作流详解
2016/10/08 Javascript
浅谈Vue网络请求之interceptors实际应用
2018/02/28 Javascript
Vue 去除路径中的#号
2018/04/19 Javascript
jQuery实现表单动态加减、ajax表单提交功能
2018/06/08 jQuery
微信小程序自定义导航教程(兼容各种手机)
2018/12/12 Javascript
vue解决花括号数据绑定不成功的问题
2019/10/30 Javascript
vant 中van-list的用法说明
2020/11/11 Javascript
详解React中共享组件逻辑的三种方式
2021/02/02 Javascript
[56:42]完美世界DOTA2联赛循环赛 Matador vs Forest 第二场 11.06
2020/11/06 DOTA
Python 代码性能优化技巧分享
2012/08/07 Python
跟老齐学Python之大话题小函数(1)
2014/10/10 Python
使用python读取txt文件的内容,并删除重复的行数方法
2018/04/18 Python
Python生成MD5值的两种方法实例分析
2019/04/26 Python
简单易懂Pytorch实战实例VGG深度网络
2019/08/27 Python
Django2 连接MySQL及model测试实例分析
2019/12/10 Python
python对数组进行排序,并输出排序后对应的索引值方式
2020/02/28 Python
Python3.7将普通图片(png)转换为SVG图片格式(网站logo图标)动起来
2020/04/21 Python
宝塔面板成功部署Django项目流程(图文)
2020/06/22 Python
通用的Django注册功能模块实现方法
2021/02/05 Python
Myprotein俄罗斯官网:欧洲第一运动营养品牌
2019/05/05 全球购物
adidas爱尔兰官方网站:阿迪达斯运动鞋和运动服
2019/11/01 全球购物
瑞典耳机品牌:URBANISTA
2019/12/03 全球购物
C语言开发工程师测试题
2016/12/20 面试题
学生个人求职自荐信格式
2013/09/23 职场文书
应届毕业生专业个人求职自荐信格式
2013/11/20 职场文书
信息科学与技术专业求职信范文
2014/02/20 职场文书
2015年党风廉政建设目标责任书
2015/05/08 职场文书
亮剑精神观后感
2015/06/05 职场文书
幼儿园园长新年寄语
2015/08/17 职场文书
2019关于垃圾分类处理的调查报告
2019/12/26 职场文书
Springboot如何使用logback实现多环境配置?
2021/06/16 Java/Android