PHP code example of zqhong / redis-ranking
1. Go to this page and download the library: Download zqhong/redis-ranking library . Choose the download type require .
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
zqhong / redis-ranking example snippets
Predis\Client;
use Zqhong\RedisRanking\Ranking\TotalRanking;
use Zqhong\RedisRanking\RankingManger;
use Zqhong\RedisRanking\Test\Fixture\DummyTotalDataSource;
$redisClient = new Client([
'scheme' => 'tcp',
'host' => '127.0.0.1',
'port' => 6379,
'password' => 'secret',
'database ' => 1,
]);
$rankingManager = (new RankingManger())
// 这里的 DataSource 类需要自己实现
->setDataSource(new DummyTotalDataSource())
// 设置需要获取的排行数据,目前有:
// 总排行、日排行、周排行、月排行、季排行、年排行
->setRankingClasses([
TotalRanking::class,
])
// 设置当前排行数据的 namespace
->setRankingName('test')
// 注入 Redis 客户端
->setRedisClient($redisClient)
// 初始化
->init();
// 获取总排行榜中前三名用户的数据(带分数)
$rankingManager->totalRanking->top(3);
// 获取总排行榜中前三名用户的数据(不带分数)
$rankingManager->totalRanking->top(3, false);
// 获取用户 akira 的排名(总排行榜中)
$rankingManager->totalRanking->rank('akira');
// 获取用户 akira 的分数(总排行榜中)
$rankingManager->totalRanking->score('akira');
// 添加一条分数变更记录(总排行榜)
// 如果用户 test 不存在,则会添加该用户,分数为 1
// 如果用户 test 已存在,该用户的分数则会在原分数基础上 + 1
$rankingManager->totalRanking->add('test', 1);
// 获取参与该排行榜的人数
echo $rankingManager->totalRanking->cardinality();