本範例參考 CodeIgniter 框架的購物車類別設計,使用純 PHP 實作一個功能完整、可直接投入生產環境的購物車核心類別。採用 Session 儲存資料,支援商品的增刪改查、金額統計、選項管理等電商核心功能。
<?php
/**
* 購物車核心類別
* 參考 CodeIgniter Cart Library 設計
*/
class Cart {
// 驗證規則
private $product_id_rule = '\.a-z0-9-_'; // 商品ID允許字元
private $product_name_rule = '\.\:a-z0-9-_'; // 商品名稱允許字元
private $debug = TRUE; // 除錯模式
// 購物車資料結構
private $_cart_contents = array();
public function __construct() {
// 從 Session 恢復購物車
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) === TRUE) $save_cart = TRUE;
} else {
foreach ($items as $val) {
if (is_array($val) && isset($val['id'])) {
if ($this->_insert($val) === TRUE) $save_cart = TRUE;
}
}
}
if ($save_cart) { $this->_save_cart(); return TRUE; }
return FALSE;
}
/** 更新商品數量 */
public function update($items = array()) {
if (!is_array($items) || count($items) == 0) return FALSE;
$save_cart = FALSE;
if (isset($items['rowid']) && isset($items['qty'])) {
if ($this->_update($items) === TRUE) $save_cart = TRUE;
} else {
foreach ($items as $val) {
if (is_array($val) && isset($val['rowid']) && isset($val['qty'])) {
if ($this->_update($val) === TRUE) $save_cart = TRUE;
}
}
}
if ($save_cart) { $this->_save_cart(); return TRUE; }
return FALSE;
}
/** 獲取總金額 */
public function total() { return $this->_cart_contents['cart_total']; }
/** 獲取商品種類數 */
public function total_items() { return $this->_cart_contents['total_items']; }
/** 獲取完整購物車內容 */
public function contents() { return $this->_cart_contents; }
/** 獲取商品選項 */
public function options($rowid = '') {
return $this->has_options($rowid) ? $this->_cart_contents[$rowid]['options'] : array();
}
/** 清空購物車 */
public function destroy() {
unset($this->_cart_contents);
$this->_cart_contents['cart_total'] = 0;
$this->_cart_contents['total_items'] = 0;
unset($_SESSION['cart_contents']);
}
// ==================== 私有方法 ====================
private function _insert($items) {
// 參數驗證:必填欄位 id, qty, price, name
// 數量/價格清洗與驗證
// ID/名稱格式驗證
// 生成唯一 rowid (含選項時用 MD5(id+options))
// 寫入購物車陣列
return TRUE; // 簡化顯示,完整程式碼見原文
}
private function _update($items) {
// 驗證 rowid 存在
// 數量清洗驗證
// 數量為 0 時移除商品,否則更新數量
return TRUE;
}
private function _save_cart() {
// 重新計算 total_items、cart_total、各商品 subtotal
// 寫回 Session
// 購物車為空時清除 Session
}
private function _log($msg) {
return @file_put_contents('cart_err.log', $msg, FILE_APPEND);
}
}
<?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'
)
);
// 更新測試:修改 rowid 對應商品數量為 21
$arr = array('rowid' => '86dbb7cb58a667558b4bbb1f60330028', 'qty' => 21);
$cart = new Cart();
$cart->insert($items);
$cart->update($arr);
var_dump($cart->contents());
// $cart->destroy(); // 清空測試
md5(id + options) 區分同款不同規格商品實際專案中可考慮加入:購物車過期自動清理、優惠券/折扣計算、庫存即時檢查、多幣別支援、資料庫持久化選項(針對登入會員)等功能。