具体如下:
redis=new Redis();
$this->redis->connect('127.0.0.1',6379);
}
//私有化的克隆方法
private function __clone()
{
}
//公有的静态方法
static public function getInstance()
{
if(!(self::$_instance instanceof self)){
self::$_instance = new CartSingleton();
}
return self::$_instance;
}
/**
* 加入购物车
*
* @author YING
* @param userId goodsName goodsId 用户id 商品名称 商品id
* @return int
*/
public function addCart($userId,$goodsName,$goodsId)
{
$hashKey="user_".$userId; //hash键名
$key=$goodsId."_".$goodsName;//键名
//加入
return $this->redis->hIncrBy($hashKey,$key,1);
}
/**
* 单删
*
* @author YING
* @param userId goodsId
* @return
*/
public function cartDelOne($userId,$goodsId)
{
$hashKey="user_".$userId; //hash键名
$key=$goodsId;//键名
//删除
return $this->redis->hDel($hashKey,$key);
}
/**
* 清空购物车
*
* @author YING
* @param userId
* @return void
*/
public function cartDelAll($userId)
{
$hashKey="user_".$userId; //hash键名
//删除
return $this->redis->del($hashKey);
}
/**
* 购物车列表
*
* @author YING
* @param userId
* @return void
*/
public function cartList($userId)
{
$hashKey="user_".$userId; //hash键名
//查询数据
return $this->redis->hGetAll($hashKey);
}
}
//实例化类
$obj=CartSingleton::getInstance();