如何用PHP写一个购物车类呢,下面我们来简单分析学习下。
代码
namespace app\common\helper; use app\common\model\Cart; use app\common\model\GoodsMain; class CartHelper { protected $cart; protected $cartList; public function __construct() { $this->cart = new Cart(); $this->cartList = array(); } // 添加到购物车 public function push($good_main_id, $good_num) { if (!session("?user")) { $this->cartList = session('cartList'); if (isset($this->cartList[$good_main_id])) { $this->cartList[$good_main_id] = $this->cartList[$good_main_id] + $good_num; } else { $this->cartList[$good_main_id] = $good_num; } session('cartList', $this->cartList); } else { $user = session('user'); $cartList = $user->cart()->where('goods_main_id', '=', $good_main_id)->find(); if ($cartList) { $cartList->goods_num = $cartList->goods_num + $good_num; $cartList->save(); } else { $user->cart()->save(["goods_main_id"=>$good_main_id, "goods_num"=>$good_num]); } } } // 删除购物车 public function del($good_main_id) { if (!is_array($good_main_id)) { $good_main_id[] = $good_main_id; } if (!session("?user")) { // 未登录用户 删除 session $this->cartList = session('cartList'); foreach ($good_main_id as $id) { if (isset($this->cartList[$id])) { unset($this->cartList[$id]); } } session('cartList', $this->cartList); } else { // 登录用户 从数据库中删除购物车 Cart::where([ ["goods_main_id","in", $good_main_id], ["user_id", "=", session("user.id")], ])->delete(); } } // 清空购物车 public function clear() { if (!session("?user")) { session('cartList', null); } else { Cart::where([ ["user_id", "=", session("user.id")] ])->delete(); } } // 购物车清单 public function list() { if (session('?user')) { $user = session('user'); $cartlist = $user->cart()->select(); $list = array(); if (!$cartlist->isEmpty()) { foreach ($cartlist as $k=>$v) { $good = GoodsMain::find($v->goods_main_id); if ($good) { $temp["good"] = $good; $temp["goods_num"] = $v->goods_num; $list[] = $temp; } } } } else { $cartlist = session('cartList'); $list = array(); if (!empty($cartlist)) { foreach ($cartlist as $k=>$v) { $good = GoodsMain::find($k); if ($good) { $temp["good"] = $good; $temp["goods_num"] = $v; $list[] = $temp; } } } } return $list; } // 合并购物车 登录前和登录后 public function merge() { if (!session('?user') || !session('?cartList')) { return false; } $user = session('user'); $cartList = session('cartList'); $updateArr = array(); foreach ($cartList as $k=>$v) { $cart = $user->cart()->where("goods_main_id","=",$k)->find(); if ($cart) { $updateArr[] = [ 'id' => $cart->id, 'goods_main_id' => $k, 'goods_num' => $cart->goods_num + $v ]; } else { $updateArr[] = [ 'goods_main_id' => $k, 'goods_num' => $v ]; } } if (!empty($updateArr)) { $user->cart()->saveAll($updateArr); } session('cartList', null); } }
分析
添加购物车有两种一情况,一种是用户已经登录,另一种是没有登录。登录的可以直接写入数据库,没有登录的可以用session保存。为了兼容两种情况,所有操作都判断了用户是否登录。还要考虑用户原本购物车里已经有产品,在没有登录前购物车里也有产品,在用户登录时需要进行合并操作,上面有代码可以参考。
保存到session的数据格式和用thinkphp6从数据库里取出的数据格式是不一样的,为了方便类的调用,也做了相应的处理。
购物车里只保存了产品的ID和数量。
虽然很简陋,但这也是我能想出来的最好的了,一起加没。