当前位置:首页 > PHP教程 > php应用 > 列表

PHP+redis实现的购物车单例类示例

发布:smiling 来源: PHP粉丝网  添加日期:2021-11-06 21:14:21 浏览: 评论:0 

这篇文章主要介绍了PHP+redis实现的购物车单例类,涉及php连接、操作redis数据库及购物车功能相关定义与使用技巧,需要的朋友可以参考下。

本文实例讲述了PHP+redis实现的购物车单例类,分享给大家供大家参考,具体如下:

  1. <?php 
  2. /** 
  3.  * 购物车单例类 
  4.  * 
  5.  * @author YING 
  6.  * @param void 
  7.  * @return void 
  8.  */ 
  9. class CartSingleton 
  10. { 
  11.   //定义一个静态的私有变量 
  12.   static private $_instance=null; 
  13.   private $redis=null; 
  14.   //私有化的构造方法 
  15.   private final function __construct() 
  16.   { 
  17.     //实例化 
  18.     $this->redis=new Redis(); 
  19.     $this->redis->connect('127.0.0.1',6379); 
  20.   } 
  21.   //私有化的克隆方法 
  22.   private function __clone() 
  23.   { 
  24.   } 
  25.   //公有的静态方法 
  26.   static public function getInstance() 
  27.   { 
  28.     if(!(self::$_instance instanceof self)){ 
  29.       self::$_instance = new CartSingleton(); 
  30.     } 
  31.     return self::$_instance; 
  32.   } 
  33.   /** 
  34.    * 加入购物车 
  35.    * 
  36.    * @author YING 
  37.    * @param userId goodsName goodsId 用户id 商品名称 商品id 
  38.    * @return int 
  39.    */ 
  40.    public function addCart($userId,$goodsName,$goodsId) 
  41.    { 
  42.      $hashKey="user_".$userId; //hash键名 
  43.      $key=$goodsId."_".$goodsName;//键名 
  44.      //加入 
  45.      return $this->redis->hIncrBy($hashKey,$key,1); 
  46.    } 
  47.   /** 
  48.    * 单删 
  49.    * 
  50.    * @author YING 
  51.    * @param userId goodsId 
  52.    * @return 
  53.    */ 
  54.   public function cartDelOne($userId,$goodsId) 
  55.   { 
  56.     $hashKey="user_".$userId; //hash键名 
  57.     $key=$goodsId;//键名 
  58.     //删除 
  59.     return $this->redis->hDel($hashKey,$key); 
  60.   } 
  61.   /** 
  62.    * 清空购物车 
  63.    * 
  64.    * @author YING 
  65.    * @param userId 
  66.    * @return void 
  67.    */ 
  68.   public function cartDelAll($userId) 
  69.   { 
  70.     $hashKey="user_".$userId; //hash键名 
  71.     //删除 
  72.     return $this->redis->del($hashKey); 
  73.   } 
  74.   /** 
  75.    * 购物车列表 
  76.    * 
  77.    * @author YING 
  78.    * @param userId 
  79.    * @return void 
  80.    */ 
  81.   public function cartList($userId) 
  82.   { 
  83.     $hashKey="user_".$userId; //hash键名 
  84.     //查询数据 
  85.     return $this->redis->hGetAll($hashKey); 
  86.   } 
  87. } 
  88. //实例化类 
  89. $obj=CartSingleton::getInstance();

Tags: PHP+redis PHP购物车单例类

分享到: