| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101 | 
							- <?php
 
- namespace app\common\controller;
 
- use Redis;
 
- /**
 
-  * 使用rediszset的排行榜
 
-  * @author harry.lv
 
-  *
 
-  */
 
- class RedisLeaderboard
 
- {
 
-     /**
 
-      *
 
-      * @var object redis client
 
-      */
 
-     private $redis;
 
-     /**
 
-      *
 
-      * @var string 放置排行榜的key
 
-      */
 
-     private $leaderboard;
 
-     /**
 
-      * 构造函数
 
-      * @param object $redis 已连接redis的phpredis的对象
 
-      * @param string $leaderboard 字符串,排行榜的key名
 
-      */
 
-     public function __construct($leaderboard = '') {
 
-         $this->redis = new \Redis();
 
-         $this->redis->connect('127.0.0.1');
 
-         $this->leaderboard = $leaderboard;
 
-     }
 
-     /**
 
-      * 获取当前的排行榜的key名
 
-      * @return string
 
-      */
 
-     public function getLeaderboard()
 
-     {
 
-         return $this->leaderboard;
 
-     }
 
-     /**
 
-      * 将对应的值填入到排行榜中
 
-      * @param  $node 对应的需要填入的值(比如用户的id)
 
-      * @param number $count 对应的值,默认值为1
 
-      * @return Long 1 if the element is added. 0 otherwise.
 
-      */
 
-     public function addLeaderboard($node, $count = 1)
 
-     {
 
-         return $this->redis->zAdd($this->leaderboard, $count, $node);
 
-     }
 
-     /**
 
-      * 给出对应的排行榜
 
-      * @param int $number 需要给出排行榜数目
 
-      * @param bool $asc 排序顺序 true为按照高分为第0
 
-      * @param bool $withscores 是否需要分数
 
-      * @param callback $callback 用于处理排行榜的回调函数
 
-      * @return [] 对应排行榜
 
-      */
 
-     public function getLeadboard($number, $asc = true, $withscores = false,$callback = null)
 
-     {
 
-         if ($asc) {
 
-             $nowLeadboard =  $this->redis->zRevRange($this->leaderboard, 0, $number -1, $withscores);//按照高分数顺序排行;
 
-         } else {
 
-             $nowLeadboard =  $this->redis->zRange($this->leaderboard, 0, $number -1, $withscores);//按照低分数顺序排行;
 
-         }
 
-         if ($callback) {
 
-             //使用回调处理
 
-             return $callback($nowLeadboard);
 
-         } else {
 
-             return $nowLeadboard;
 
-         }
 
-     }
 
-     /**
 
-      * 获取给定节点的排名
 
-      * @param string $node 对应的节点的key名
 
-      * @param string $asc 是否按照分数大小正序排名, true的情况下分数越大,排名越高
 
-      * @return 节点排名,根据$asc排序,true的话,第一高分为0,false的话第一低分为0
 
-      */
 
-     public function getNodeRank($node, $asc = true)
 
-     {
 
-         if ($asc) {
 
-             //zRevRank 分数最高的排行为0,所以需要加1位
 
-             return $this->redis->zRevRank($this->leaderboard, $node);
 
-         } else {
 
-             return $this->redis->zRank($this->leaderboard, $node);
 
-         }
 
-     }
 
-     /**
 
-      * 计算给定的一个或多个有序集的并集
 
-      */
 
-     public function getZunionstore() {
 
-         $this->redis->zUnionStore();
 
-     }
 
- }
 
 
  |