首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 綜合知識

PHP 實作購物車類別完整範例(CodeIgniter 風格)

     編輯:PHP 綜合知識

專案背景

本範例參考 CodeIgniter 框架的購物車類別設計,使用純 PHP 實作一個功能完整、可直接投入生產環境的購物車核心類別。採用 Session 儲存資料,支援商品的增刪改查、金額統計、選項管理等電商核心功能。

核心功能清單

  1. 商品加入購物車(支援單筆/批次)
  2. 移除指定商品
  3. 更新商品數量(+1/-1/直接設定)
  4. 購物車統計:總項目數、總數量、總金額
  5. 單一商品小計統計
  6. 清空購物車
  7. 商品選項支援(如顏色、尺寸等屬性)

核心類別結構

Cart.php 完整實作

<?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);
    }
}

使用示範

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'
    )
);

// 更新測試:修改 rowid 對應商品數量為 21
$arr = array('rowid' => '86dbb7cb58a667558b4bbb1f60330028', 'qty' => 21);

$cart = new Cart();
$cart->insert($items);
$cart->update($arr);
var_dump($cart->contents());
// $cart->destroy(); // 清空測試

關鍵設計亮點

  • RowID 機制:使用 md5(id + options) 區分同款不同規格商品
  • 資料清洗:自動移除數量/價格中的非數字字元與前導零
  • 輸入驗證:嚴格的正則規則防止惡意資料注入
  • Session 持久化:自動同步記憶體與 Session 資料
  • 除錯支援:內建日誌記錄便於問題追蹤

擴展建議

實際專案中可考慮加入:購物車過期自動清理、優惠券/折扣計算、庫存即時檢查、多幣別支援、資料庫持久化選項(針對登入會員)等功能。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved