簡易購物車類別架構:商品與購物車分離設計
商品類別
_partNumber = $partNumber;
$this->_description = $description;
$this->_price = $price;
}
public function getPartNumber() { return $this->_partNumber; }
public function getDescription() { return $this->_description; }
public function getPrice() { return $this->_price; }
}
?>
購物車類別
_products);
}
// 計算總金額
public function getCartTotal() {
$sum = 0;
for ($i = 0, $cnt = count($this); $i < $cnt; $i++) {
$sum += $this[$i]->getPrice();
}
return $sum;
}
// 新增商品(利用 ArrayObject 特性)
public function addProduct(Product $product) {
$this[] = $product;
}
// 移除商品
public function removeProduct($index) {
if (isset($this[$index])) {
unset($this[$index]);
}
}
// 取得商品數量
public function getItemCount() {
return count($this);
}
}
?>
使用範例
addProduct(new Product('SKU-001', '無線滑鼠', 599));
$cart->addProduct(new Product('SKU-002', '機械鍵盤', 2490));
$cart->addProduct(new Product('SKU-003', '螢幕支架', 890));
echo "商品數量:{$cart->getItemCount()} 件
";
echo "總金額:NT$ {$cart->getCartTotal()} 元
";
// 列出明細
foreach ($cart as $index => $product) {
echo "{$index}. {$product->getDescription()} ({$product->getPartNumber()}) - NT$ {$product->getPrice()}
";
}
?>
設計重點與擴充建議
- 繼承 ArrayObject:直接獲得陣列操作介面(
[]、count()、foreach),程式碼簡潔。
- 單一職責:Product 只負責資料封裝,Cart 負責集合管理與業務邏輯。
- 擴充方向:
- 加入數量欄位(需改為關聯陣列或引入 CartItem 類別)
- 整合 Session 持久化(
serialize()/unserialize())
- 加入優惠碼、運費、稅金計算邏輯
- 實作
Iterator、Countable、JsonSerializable 介面