购物车服务 - 代码示例

CartService::addToCart() - 添加购物车
use app\common\service\CartService; // 添加商品到购物车 $result = CartService::addToCart( 'user123', // 会员ID 5, // 产品ID 2 // 数量 ); // 返回: ['status' => 1, 'msg' => '添加成功'] // 或: ['status' => 0, 'msg' => '库存不足']
CartService::getCart() - 获取购物车
// 获取会员购物车 $cart = CartService::getCart('user123'); // 返回: 购物车数组 // 包含: 商品列表、总数量、总金额 // 结构: // [ // 'items' => [ // ['product_id'=>5, 'title'=>'商品名', // 'price'=>100, 'qty'=>2, 'subtotal'=>200], // ], // 'total_qty' => 2, // 'total_amount' => 200, // ]
CartService::clearCart() - 清空购物车
// 清空会员购物车 $result = CartService::clearCart('user123'); // 返回: true/false // 用途: 订单提交后清空购物车

CartService 说明

购物车数据存储

购物车数据存储在 Session 中,以会员ID为键。

每个商品包含: product_id, title, price, qty, subtotal

使用场景

1. 产品详情页点击"加入购物车"

2. 购物车页面查看、修改数量

3. 结算页面计算总价

4. 订单提交后清空购物车