1.商品列表中点击加入购物车,则跳转到购物车列表,效果如图所示:
视图代码goods/list.php中。代码如下:
<?php echo Html::a('加入购物车',['cart','id'=>$info['goods_id']])?>
控制器GoodsController.php中,开启session.
use yii\web\Session; $session = new Session; $session->open();
/** * 加入购物车 */ public function actionCart($id){ //获取添加到购物车的商品的信息 $goods_model=new Goods(); $good_info=$goods_model->findOne($id); //信息为空或者数量<0,则不存在要购买的商品,否则把要购买的商品添加到session中 if(empty($good_info) || count($good_info)<0){ exit("No Goods"); }else{ $good_info['num']=1; //判断购物车中是否已经存在该商品,存在的话数量叠加, if(isset($_SESSION["shoplist"][$good_info['goods_id']])){ //若存在数量叠加 $num=$_SESSION["shoplist"][$good_info['goods_id']]['num']; $num++; $_SESSION["shoplist"][$good_info['goods_id']]['num']=$num; //$_SESSION["shoplist"][$good_info['goods_id']]['num'] ++; }else{ //若不存在,作为新购买的商品添加到购物车中 $_SESSION["shoplist"][$good_info['goods_id']]=$good_info; } // $_SESSION['shoplist'][]=$good_info; return $this->redirect('./index.php?r=cart/list'); } }
2.购物车列表页:
use yii\web\Session; $session = new Session; $session->open();
/** * 购物车列表 */ public function actionList(){ $cart_list=$_SESSION['shoplist']; return $this->render('list',['cart_list'=>$cart_list]); }
3.删除购物车中的商品和清空购物车
视图cart/list.php中 $info['goods_id']],['onclick'=> 'return confirm("Confirm to delete?")'])?>
控制器CartController.php中 /** * 购物车中的单一商品删除 */ public function actionDelete(){ $cart_list=$_SESSION['shoplist']; //判断是删除一个商品还是请空购物车 if($_GET['id']){ //从session中删除指定的商品信息 unset($_SESSION["shoplist"][$_GET['id']]); }else{ //清空session中商品,清空购物车 unset($_SESSION["shoplist"]); } return $this->redirect("./index.php?r=cart/list"); }