<?php
// 服务层
namespace Common\Service;
use Vendor\Func\Red;
class CartService extends CommonService {
protected $redis;
protected $pre_key;
public function __construct()
{
parent::__construct();
$this->redis = Red::create();
$this->pre_key = C('USER.CART').C('APPID').':';
}
/**
* 加入购物车,移除购物车,但是不会删除
* @param $openid
* @param $sku_id
* @param int $count
* @return mixed
*/
public function add($openid, $sku_id, $count = 1)
{
$key = $this->pre_key.$openid;
// 可增可减
return $this->redis->hIncrBy($key, $sku_id, $count);
}
/**
* 批量添加
* @param $openid
* @param array $data
* @return mixed
*/
public function addBatch($openid, array $data)
{
$key = $this->pre_key.$openid;
// 批量执行
$r = $this->redis->multi(\Redis::PIPELINE);
foreach ($data as $k => $v) {
$r = $r->hIncrBy($key, $k, $v);
}
return $this->redis->exec();
}
/**
* 删除购物车单个商品
* @param $openid
* @param $sku_id
* @return mixed
*/
public function delete($openid, $sku_id)
{
$key = $this->pre_key.$openid;
return $this->redis->hdel($key, $sku_id);
}
/**
* 删除购物车多个商品
* @param $openid
* @param $sku_ids
* @return bool
*/
public function deleteBatch($openid, $sku_ids)
{
$key = $this->pre_key.$openid;
foreach ($sku_ids as $k => $v) {
$this->redis->hdel($key, $v);
}
return true;
}
/**
* 检测商品是否已在购物车中
* @param $openid
* @param $sku_id
* @return mixed
*/
public function exists($openid, $sku_id)
{
$key = $this->pre_key.$openid;
return $this->redis->hExists($key, $sku_id);
}
/**
* 清空购物车
* @param $openid
* @return mixed
*/
public function deleteAll($openid)
{
$key = $this->pre_key.$openid;
return $this->redis->del($key);
}
/**
* 判断购物车中是否有数据,有多少
* @param $openid
* @return mixed
*/
public function hasUserCart($openid)
{
$key = $this->pre_key.$openid;
return $this->redis->hLen($key);
}
/**
* 设置为固定数量
* @param $openid
* @param $sku_id
* @param $count
* @return bool
*/
public function setCount($openid, $sku_id, $count)
{
$key = $this->pre_key.$openid;
$status = $this->redis->hset($key, $sku_id, $count);
if ((int)$status === -1) {
return false;
}
return true;
}
/**
* 获取购物车中单个商品的数量
* @param $openid
* @param $sku_id
* @return mixed
*/
public function getCount($openid, $sku_id)
{
$key = $this->pre_key.$openid;
return $this->redis->hget($key, $sku_id);
}
/**
* 获取全部数据
* @param $openid
* @return mixed
*/
public function getAll($openid)
{
$key = $this->pre_key.$openid;
return $this->redis->hgetall($key);
}
/**
* 获取全部商品id
* @param $openid
* @return mixed
*/
public function getAllKeys($openid)
{
$key = $this->pre_key.$openid;
return $this->redis->hkeys($key);
}
/**
* 获取全部商品数量
* @param $openid
* @return mixed
*/
public function getAllVal($openid)
{
$key = $this->pre_key.$openid;
return $this->redis->hvals($key);
}
}
加入购物车,移除购物车,清空购物车,查看购物车数量,查看全部商品等等。
扫码二维码 获取免费视频学习资料
- 本文固定链接: http://phpxs.com/post/7321/
- 转载请注明:转载必须在正文中标注并保留原文链接
- 扫码: 扫上方二维码获取免费视频资料