直接看代码:
// 服务层namespace CommonService;
use VendorFuncRed;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);}
}
加入购物车,移除购物车,清空购物车,查看购物车数量,查看全部商品等等。
以上内容希望帮助到大家,很多PHPer在进阶的时候总会遇到一些问题和瓶颈,业务代码写多了没有方向感,不知道该从那里入手去提升,对此我整理了一些资料,包括但不限于:分布式架构、高可扩展、高性能、高并发、服务器性能调优、TP6,laravel,YII2,Redis,Swoole、Swoft、Kafka、Mysql优化、shell脚本、Docker、微服务、Nginx等多个知识点高级进阶干货需要的可以免费分享给大家,需要
PHP进阶架构师>>>视频、面试文档免费获取shimo.im
或 者关注咱们下面的知乎专栏
PHP架构师圈子zhuanlan.zhihu.com