Lesson 2
Using Sorted Sets for Leaderboards
Using Sorted Sets for Leaderboards

Welcome to the next exciting part of our Redis-based backend system project. In this unit, we will focus on building leaderboard functionality using Redis's sorted sets with PHP. Building a leaderboard is a popular use case for many applications, such as games and competitive platforms. You’ve got a good handle on managing user data from previous lessons, so let’s build on that foundation.

What You'll Build

Let's briefly review what we’ll focus on in this unit. Our main tasks will be:

  1. Adding user scores to a leaderboard: We will store user scores using Redis sorted sets.
  2. Retrieving the leaderboard: We will fetch and display the top users and their scores.
  3. Getting a user's rank and score: We will retrieve the ranking and score of a specific user.

Below are some key parts of the code you will be working with to perform these tasks.

php
1<?php 2 3require 'vendor/autoload.php'; 4 5Predis\Autoloader::register(); 6 7// Connect to Redis 8$client = new Predis\Client([ 9 'scheme' => 'tcp', 10 'host' => '127.0.0.1', 11 'port' => 6379, 12]); 13 14// Add user scores to the leaderboard 15$client->zadd('leaderboard', 100, 'user1'); 16$client->zadd('leaderboard', 200, 'user2'); 17$client->zadd('leaderboard', 150, 'user3'); 18 19// Retrieve top users 20$leaderboard = $client->zrevrange('leaderboard', 0, 2, ['withscores' => true]); 21print_r($leaderboard); 22 23// Get user rank 24$rank = $client->zrevrank('leaderboard', 'user3'); 25 26// Get user score 27$score = $client->zscore('leaderboard', 'user3'); 28echo "Rank: $rank, Score: $score\n";

This example demonstrates how to add a score for a user, retrieve the top scores, and fetch a user’s rank and score using PHP. You are familiar with the zadd and zrevrange commands from previous lessons. These commands are used to add scores and retrieve the leaderboard, respectively.

Explanation of Commands

Now let's understand the zrevrank and zscore commands. The zrevrank command returns the rank of a member in a sorted set, with the highest score being ranked first. The zscore command retrieves the score of a member in a sorted set. They both receive the set name and the member as parameters.

Now that you have an overview, let's dive into the practice section to start implementing these components. Your hands-on work will strengthen your understanding, setting you up for success in creating robust backend features.

Enjoy this lesson? Now it's time to practice with Cosmo!
Practice is how you turn knowledge into actual skills.