PHP code example of wangjian / ranking

1. Go to this page and download the library: Download wangjian/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/ */

    

wangjian / ranking example snippets


//定义provider
class AllProvider extends \Wangjian\Ranking\Provider\AllProvider
{
    public function getAll()
    {
        $items = [];

        for($i = 0; $i < 10; $i++) {
            $items[] = [
                'score' => rand(0, 100),
                'member' => $this->getRandomMember()
            ];
        }

        return $items;
    }

    protected function getRandomMember($length = 6)
    {
        $tokens = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
        $tokenCount = strlen($tokens);

        $str = '';
        for($i = 0; $i < $length; $i++) {
            $str .= $tokens[rand(0, $tokenCount-1)];
        }

        return $str;
    }
}

//从数据库中获取数据
class DatabaseAllProvider extends \Wangjian\Ranking\Provider\AllProvider
{
    public function getAll()
    {
        //链接数据库
        $pdo = new PDO('', '', '');

        $select = 'SELECT score, member from tb';
        $sth = $pdo->query($select);
        return $sth->fetchAll(PDO::FETCH_ASSOC);
    }
}

//定义PageProvider
class DatabasePageProvider extends \Wangjian\Ranking\Provider\PageProvider
{
    public function getPage($page)
    {
        //定义每页加载条数
        $perPage = 100;

        //链接数据库
        $pdo = new PDO('', '', '');

        $select = 'SELECT score, member from tb LIMIT ' . ($page - 1) * $perPage . ', ' . $perPage;
        $sth = $pdo->query($select);
        return $sth->fetchAll(PDO::FETCH_ASSOC);
    }
}

//定义GeneratorProvider
class DatabaseGeneratorProvider extends \Wangjian\Ranking\Provider\GeneratorProvider
{
    public function generate()
    {
        //链接数据库
        $pdo = new PDO('', '', '');

        $select = 'SELECT score, member from tb LIMIT ' . ($page - 1) * $perPage . ', ' . $perPage;
        $sth = $pdo->query($select)->setFetchMode(PDO::FETCH_ASSOC);
        foreach($sth as $row) {
            yield $row;
        }
    }
}

//链接redis
$client = new \Predis\Client([
    'scheme' => 'tcp',
    'host' => '127.0.0.1',
    'port' => 6379,
    'password' => 'root'
]);

//排行榜名称
$prefix = 'score';

//总排行榜
$totalRanking1 = new \Wangjian\Ranking\Ranking\TotalRanking($client, new DatabaseAllProvider(), $prefix);
$totalRanking2 = new \Wangjian\Ranking\Ranking\TotalRanking($client, new DatabasePageProvider(), $prefix);
$totalRanking3 = new \Wangjian\Ranking\Ranking\TotalRanking($client, new DatabaseGeneratorProvider(), $prefix);

//日排行榜
$dailyRanking = new \Wangjian\Ranking\Ranking\DailyRanking($client, new DatabaseAllProvider(), $prefix);

//周排行榜
$weeklyRanking = new \Wangjian\Ranking\Ranking\WeeklyRanking($client, new DatabaseAllProvider(), $prefix);

//月排行榜
$monthlyRanking = new \Wangjian\Ranking\Ranking\MonthlyRanking($client, new DatabaseAllProvider(), $prefix);

//历史日排行榜
$previousDailyRanking = new \Wangjian\Ranking\Ranking\PreviousDailyRanking($client, new DatabaseAllProvider(), $prefix);

//历史周排行榜
$previousWeeklyRanking = new \Wangjian\Ranking\Ranking\PreviousWeeklyRanking($client, new DatabaseAllProvider(), $prefix);

//历史月排行榜
$previousMonthlyRanking = new \Wangjian\Ranking\Ranking\PreviousMonthlyRanking($client, new DatabaseAllProvider(), $prefix);

//获取从1名到100名之间的信息
$rankingInfo = $totalRanking1->top(1, 100);  //返回信息带上score  $rankingInfoWithScore = $totalRanking1->top(1, 100, true);

//获取某个成员的具体排名
$position = $totalRanking1->rank('someone');  //返回信息带上score  $positionWithScore = $totalRanking1->rank('someone', true);

//新增一条记录,张三,分数为20,更新排行榜
$totalRanking1->addItem('zhangsan', 20);

//实例化RankingManager
$manager = new \Wangjian\Ranking\RankingManager($client, $prefix);

//增加排行榜
$manager->addRanking(\Wangjian\Ranking\Ranking\TotalRanking::class, new DatabaseAllProvider());
$manager->addRanking(\Wangjian\Ranking\Ranking\DailyRanking::class, new DatabaseAllProvider(), 'daily'); //设置别名

//初始化,一定要初始化,才能获取排行榜
$manager->init();

//我们可以使用addRanking函数里面的别名来获取排行榜对象,如果没有设置别名,则默认使用首字母小写的类名
$totalRanking4 = $manager->totalRanking;  //由于没有设置别名,默认使用totalRanking
$dailyRanking2 = $manager->daily;  //使用别名获取

//更新排行榜
$manager->addItem('lisi', 30);

class HourlyRanking extends \Wangjian\Ranking\Ranking\AbstractRanking
{
    protected function getRankingName()
    {
        //返回排行榜名称,一定不能和其他排行榜冲突
        return 'hourly';
    }

    protected function needRefresh()
    {
        //redis里面的排行榜是否过期

        //获取排行榜实例化的时间,如果不存在,说明排行榜还没有初始化过
        if(($initTimestamp = $this->getInitTime()) === false) {
            return true;
        }

        return $initTime < strtotime(date('Y-m-d H:00:00')) || $initTime > strtotime(date('Y-m-d H:59:59'));
    }

    protected function isRealTime()
    {
        //排行榜是否是实时的
        return true;
    }
}