群里有人问这个Redis存储用户购物车信息,我简单的写了个面向过程的demo
代码如下:
<?php
$user_id=session("user_id");//获取用户登录信息
$goods_id=isset($_POST['goods_id'])?$_POST['goods_id']:0;//获取要添加的商品id
if($user_id<1)
{
die("用户不存在或者尚未登录");//用户不存在或者尚未登录
}
if($goods_id<1)
{
die("传参丢失");//传参丢失
}
$goods_info=get_goods_info_by_goods_id($goods_id);//获取商品信息
$redis_object=new Redis();//实例化Redis模型
$my_cart_info=unserialize($redis_object->get("cart_".$user_id));//获取某个人的购物车信息
if(isset($my_cart_info[$goods_id]))
{
$my_cart_info[$goods_id]['count']++;//数量加 1
}else
{
//该商品首次加入购物车
$my_cart_info[$goods_id]=array(
"count"=>1,
"info"=$goods_info
);
}
$redis_object->set("cart_".$user_id,serialize($my_cart_info));//放入Redis
echo json_encode($my_cart_info);
exit();
?>
截图如下: