功能特性
- 商品加入 / 删除 / 更新(数量 +1/-1)
- 统计:总项数、总数量、总金额
- 单项商品数量 / 金额统计
- 清空购物车
- 基于 Session 持久化,支持多维数组批量操作
核心类结构
<?php
class Cart {
// 配置规则
private $product_id_rule = '.a-z0-9-_';
private $product_name_rule = '.:a-z0-9-_';
private $debug = true;
// 购物车数据结构
private $_cart_contents = 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;
}
}
// 插入商品(支持单条/批量)
public function insert($items = array()) {
if (!is_array($items) || count($items) == 0) return false;
$save_cart = false;
if (isset($items['id'])) {
if ($this->_insert($items)) $save_cart = true;
} else {
foreach ($items as $val) {
if (is_array($val) && isset($val['id']) && $this->_insert($val)) {
$save_cart = true;
}
}
}
if ($save_cart) $this->_save_cart();
return $save_cart;
}
// 内部插入逻辑(校验、合并同款、更新统计)
private function _insert($item) {
// 省略详细校验代码...
// 生成 rowid (md5(id+options)),更新 _cart_contents
// 重新计算 cart_total, total_items
return true;
}
// 更新数量
public function update($rowid, $qty = 0) { /* ... */ }
// 删除单项
public function remove($rowid) { /* ... */ }
// 获取购物车内容
public function contents() { return $this->_cart_contents; }
// 统计总金额
public function total() { return $this->_cart_contents['cart_total']; }
// 统计总件数
public function total_items() { return $this->_cart_contents['total_items']; }
// 清空
public function destroy() {
$this->_cart_contents = array('cart_total' => 0, 'total_items' => 0);
$this->_save_cart();
}
// 持久化到 Session
private function _save_cart() {
$_SESSION['cart_contents'] = $this->_cart_contents;
}
}
使用示例
session_start();
$cart = new Cart();
// 加入商品
$cart->insert(array(
'id' => 'p001',
'name' => 'PHP 进阶教程',
'price' => 99.00,
'qty' => 2
));
// 更新数量
$cart->update($rowid, 3);
// 显示购物车
foreach ($cart->contents() as $item) {
if (is_array($item) && isset($item['id'])) {
echo "{$item['name']} × {$item['qty']} = ¥{$item['subtotal']}<br>";
}
}
echo "总计:¥{$cart->total()}";
扩展建议
- 引入数据库持久化,支持用户登录后跨设备同步购物车。
- 添加库存校验、优惠券、运费计算等业务逻辑层。
- 使用 Redis 存储 Session,提升高并发下的读写性能。