適合中小型專案、無需資料庫即可快速上線的購物車方案。資料結構採用 type:id,id|type:id,id 格式儲存於 Cookie,支援商品分類、防重複、刪除、清空等操作。本文重構原始碼,修正語法錯誤、加入型別宣告、修正正則逸出問題,並補充數量管理擴充方向。
Cookie 名稱: cart
值範例: "food:101,102|electronics:205|books:301,302,303"
結構: 類型:ID,ID|類型:ID|...
<?php
class Cart
{
private const COOKIE_NAME = 'cart';
private const COOKIE_EXPIRE = 86400 * 30; // 30 天
/** 新增商品 */
public static function add(string $type, string $id): void
{
$cart = self::getCartData();
$key = self::findTypeKey($cart, $type);
if ($key === null) {
$cart[] = "$type:$id";
} else {
$ids = explode(',', $cart[$key]);
if (!in_array($id, $ids, true)) {
$ids[] = $id;
$cart[$key] = $type . ':' . implode(',', $ids);
}
}
self::saveCart($cart);
}
/** 取得指定類型的商品 ID 陣列 */
public static function getIds(string $type): array
{
$cart = self::getCartData();
$key = self::findTypeKey($cart, $type);
if ($key === null) return [];
return explode(',', $cart[$key]);
}
/** 刪除指定商品 */
public static function remove(string $type, string $id): void
{
$cart = self::getCartData();
$key = self::findTypeKey($cart, $type);
if ($key === null) return;
$ids = explode(',', $cart[$key]);
$ids = array_filter($ids, fn($v) => $v !== $id);
if (empty($ids)) {
unset($cart[$key]);
$cart = array_values($cart); // 重建索引
} else {
$cart[$key] = $type . ':' . implode(',', $ids);
}
self::saveCart($cart);
}
/** 清空購物車 */
public static function clear(): void
{
setcookie(self::COOKIE_NAME, '', time() - 3600, '/');
}
/** 取得完整購物車資料(供前端顯示) */
public static function getAll(): array
{
$cart = self::getCartData();
$result = [];
foreach ($cart as $item) {
[$type, $idsStr] = explode(':', $item, 2);
$result[$type] = explode(',', $idsStr);
}
return $result;
}
// ===== 私有輔助方法 =====
private static function getCartData(): array
{
$cookie = $_COOKIE[self::COOKIE_NAME] ?? '';
return $cookie ? explode('|', $cookie) : [];
}
private static function findTypeKey(array $cart, string $type): ?int
{
foreach ($cart as $i => $item) {
if (str_starts_with($item, $type . ':')) {
return $i;
}
}
return null;
}
private static function saveCart(array $cart): void
{
$value = implode('|', $cart);
setcookie(self::COOKIE_NAME, $value, time() + self::COOKIE_EXPIRE, '/', '', false, true); // HttpOnly=true
}
}
<?php
require_once 'Cart.php';
// 新增商品
Cart::add('food', '101');
Cart::add('food', '102');
Cart::add('electronics', '205');
// 顯示購物車
$cart = Cart::getAll();
foreach ($cart as $type => $ids) {
echo "$type
";
foreach ($ids as $id) {
echo "- 商品 ID: $id
";
}
echo "
";
}
// 刪除商品
Cart::remove('food', '101');
// 清空
// Cart::clear();
若需支援數量、單價、小計,建議改用 JSON 結構儲存:
[
{"type": "food", "id": "101", "qty": 2, "price": 120},
{"type": "electronics", "id": "205", "qty": 1, "price": 3500}
]
對應修改 saveCart 序列化為 json_encode,getCartData 反序列化 json_decode,並調整 add/remove/getIds 邏輯即可。Cookie 容量限制 4KB,商品過多時建議改用 Session + 資料庫方案。
HttpOnly、Secure (HTTPS)、SameSite=Lax。