<?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);
}
}
加入購物車,移除購物車,清空購物車,查看購物車數量,查看全部商品等等。
