单例模式 Redis

来源:互联网 发布:灵界室友网络剧百度云 编辑:程序博客网 时间:2024/05/18 18:03
<?php//购物车单例模式class CartSingleton{    //三私一公    //定义一个静态的私变量    static private $_instance=null;    private $redis = null;    //私有的构造方法    private final function __construct(){        //实例化        $this->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;    }    //加入购物车    public function addCart($userId,$gid,$gname){        //hash键名        $hashKey = "user_".$userId;        //键名        $key = $gid."_".$gname;        //加入        //return $gname;        return $this->redis->hIncrBy($hashKey,$key,1);    }    //购物车列表    public function cartList($userId){        $hashKey = "user_".$userId;        //查询        return $this->redis->hGetAll($hashKey);    }    //清空原有的数据    public function dell($userId,$gid,$gname){        return $this->redis->flushAll();    }    //购物车单删    public function cartDel($userId,$gid,$gname){        $hashKey = "user_".$userId;        $key = $gid."_".$gname;        //删除        return $this->redis->hDel($hashKey,$key);    }    //清空购物车    public function delall($userId){        $hashKey = "user_".$userId;        return $this->redis->del($hashKey);    }}
0 0