PHP实现的购物车类实例


Posted in PHP onJune 17, 2015

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

该购物车类是基于CodeIgniter的购物车类仿写实现的。

购物车基本功能如下:

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

1. 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*/

2. 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 强制下载文件代码
Oct 24 PHP
php判断两个浮点数是否相等的方法
Mar 14 PHP
Yii2.0 模态弹出框+ajax提交表单
May 22 PHP
Windows2003下php5.4安装配置教程(Apache2.4)
Jun 30 PHP
PHP那些琐碎的知识点(整理)
May 20 PHP
Zend Framework框架中实现Ajax的方法示例
Jun 27 PHP
thinkPHP多表查询及分页功能实现方法示例
Jul 03 PHP
PHP 实现公历日期与农历日期的互转换
Sep 13 PHP
php微信支付之公众号支付功能
May 30 PHP
Laravel修改验证提示信息为中文的示例
Oct 23 PHP
Yii2框架中一些折磨人的坑
Dec 15 PHP
php连接mysql之mysql_connect()与mysqli_connect()的区别
Jul 19 PHP
CodeIgniter实现从网站抓取图片并自动下载到文件夹里的方法
Jun 17 #PHP
PHP基于MySQL数据库实现对象持久层的方法
Jun 17 #PHP
php使用curl打开https网站的方法
Jun 17 #PHP
php使用CURL不依赖COOKIEJAR获取COOKIE的方法
Jun 17 #PHP
PHP封装的HttpClient类用法实例
Jun 17 #PHP
PHP处理postfix邮件内容的方法
Jun 16 #PHP
PHP限制HTML内容中图片必须是本站的方法
Jun 16 #PHP
You might like
PHP开发大型项目的一点经验
2006/10/09 PHP
php实现的遍历文件夹下所有文件,编辑删除
2010/01/05 PHP
PHP实现显示照片exif信息的方法
2014/07/11 PHP
CodeIgniter记录错误日志的方法全面总结
2016/05/17 PHP
php自动载入类用法实例分析
2016/06/24 PHP
javascript制作坦克大战全纪录(1)
2014/11/27 Javascript
jQuery拖拽排序插件制作拖拽排序效果(附源码下载)
2016/02/23 Javascript
json实现添加、遍历与删除属性的方法
2016/06/17 Javascript
微信小程序 Storage API实例详解
2016/10/02 Javascript
原生JS实现圆环拖拽效果
2017/04/07 Javascript
vue如何引用其他组件(css和js)
2017/04/13 Javascript
EasyUI的TreeGrid的过滤功能的解决思路
2017/08/08 Javascript
vue.js $refs和$emit 父子组件交互的方法
2017/12/20 Javascript
深入理解使用Vue实现Context-Menu的思考与总结
2019/03/09 Javascript
JS实现简单打字测试
2020/06/24 Javascript
[09:37]DOTA2卡尔工作室 英雄介绍圣堂刺客篇
2013/06/13 DOTA
[58:37]Serenity vs Fnatic 2018国际邀请赛淘汰赛BO1 8.21
2018/08/22 DOTA
用Python制作简单的朴素基数估计器的教程
2015/04/01 Python
Python多层嵌套list的递归处理方法(推荐)
2016/06/08 Python
tensorflow: variable的值与variable.read_value()的值区别详解
2018/07/30 Python
解决安装pycharm后不能执行python脚本的问题
2019/01/19 Python
使用sklearn对多分类的每个类别进行指标评价操作
2020/06/11 Python
python+pygame实现坦克大战小游戏的示例代码(可以自定义子弹速度)
2020/08/11 Python
一文详述 Python 中的 property 语法
2020/09/01 Python
美国渔具店:FishUSA
2019/08/07 全球购物
关于爱情的广播稿
2014/01/16 职场文书
十月份红领巾广播稿
2014/01/22 职场文书
业务员自荐信范文
2014/04/20 职场文书
超市七夕促销活动方案
2014/08/28 职场文书
学校政风行风评议工作总结
2014/10/21 职场文书
2014年安全管理工作总结
2014/12/01 职场文书
2014年校长工作总结
2014/12/11 职场文书
鲁迅故里导游词
2015/02/05 职场文书
JavaWeb 入门篇:创建Web项目,Idea配置tomcat
2021/07/16 Java/Android
Android实现获取短信验证码并自动填充
2023/05/21 Java/Android