Skip to main content

List Leaderboards

The list leaderboards method retrieves all available leaderboards for a specific game. This is typically used to display competitive ranking options to players.

Overview

The getLeaderboards method:

  • Returns all leaderboards configured for a specific game
  • Provides leaderboard metadata including names and IDs
  • Returns an array of LeaderboardMeta objects
  • Handles empty results gracefully

Method Signature

public function getLeaderboards(string $gameID): array

Parameters

Required Parameters

  • gameID (String) - The Game ID for which to retrieve leaderboards
    • Must be a valid Moitribe Game ID
    • Cannot be empty

Return Value

Returns an array of LeaderboardMeta objects:

  • Empty array - No leaderboards found or game doesn't exist
  • Array with objects - Successfully retrieved leaderboards

Each LeaderboardMeta object contains:

  • Leaderboard ID
  • Leaderboard name
  • Leaderboard type (daily, weekly, monthly, all-time)
  • Score sorting order
  • Update frequency
  • Participant count

Basic Usage

Get All Leaderboards for a Game

use Veniso\Moitribe\Sdk\modules\classes\MoitribeApi;

$moitribe = new MoitribeApi([
'gameid' => 'your-game-id',
'channelid' => 'your-channel-id',
'playerid' => 'player-123'
]);

try {
$leaderboards = $moitribe->leaderboardRequestsHandler->getLeaderboards('your-game-id');

echo "Found " . count($leaderboards) . " leaderboards:\n";

foreach ($leaderboards as $leaderboard) {
echo "- " . $leaderboard->getName() . " (ID: " . $leaderboard->getId() . ")\n";
echo " Type: " . $leaderboard->getType() . "\n";
echo " Participants: " . $leaderboard->getParticipantCount() . "\n";
echo " Updated: " . $leaderboard->getLastUpdated() . "\n\n";
}

} catch (Exception $e) {
echo "Error: " . $e->getMessage() . "\n";
}

Filter Leaderboards by Type

function getLeaderboardsByType($gameId, $type = null) {
global $moitribe;

try {
$allLeaderboards = $moitribe->leaderboardRequestsHandler->getLeaderboards($gameId);

if ($type === null) {
return $allLeaderboards;
}

$filteredLeaderboards = array_filter($allLeaderboards, function($leaderboard) use ($type) {
return $leaderboard->getType() === $type;
});

return array_values($filteredLeaderboards);

} catch (Exception $e) {
error_log("Error getting leaderboards: " . $e->getMessage());
return [];
}
}

// Usage
$dailyLeaderboards = getLeaderboardsByType('your-game-id', 'daily');
$weeklyLeaderboards = getLeaderboardsByType('your-game-id', 'weekly');
$allTimeLeaderboards = getLeaderboardsByType('your-game-id', 'all-time');

echo "Daily Leaderboards: " . count($dailyLeaderboards) . "\n";
echo "Weekly Leaderboards: " . count($weeklyLeaderboards) . "\n";
echo "All-Time Leaderboards: " . count($allTimeLeaderboards) . "\n";

Integration Examples

Leaderboard Selection Interface

function displayLeaderboardSelection($gameId) {
global $moitribe;

try {
$leaderboards = $moitribe->leaderboardRequestsHandler->getLeaderboards($gameId);

if (empty($leaderboards)) {
echo "<p>No leaderboards available for this game.</p>";
return;
}

// Group leaderboards by type
$groupedLeaderboards = [];
foreach ($leaderboards as $leaderboard) {
$type = $leaderboard->getType();
if (!isset($groupedLeaderboards[$type])) {
$groupedLeaderboards[$type] = [];
}
$groupedLeaderboards[$type][] = $leaderboard;
}

echo "<div class='leaderboard-selection'>";
echo "<h2>Choose a Leaderboard</h2>";

foreach ($groupedLeaderboards as $type => $typeLeaderboards) {
$typeLabel = ucfirst($type);
echo "<div class='leaderboard-group'>";
echo "<h3>$typeLabel Leaderboards</h3>";

foreach ($typeLeaderboards as $leaderboard) {
$participantCount = $leaderboard->getParticipantCount();
$lastUpdated = date('M j, Y', strtotime($leaderboard->getLastUpdated()));

echo "<div class='leaderboard-item' data-id='{$leaderboard->getId()}'>";
echo "<h4>" . htmlspecialchars($leaderboard->getName()) . "</h4>";
echo "<div class='leaderboard-stats'>";
echo "<span class='participants'>$participantCount players</span>";
echo "<span class='updated'>Updated: $lastUpdated</span>";
echo "</div>";
echo "<button class='view-btn' onclick='viewLeaderboard(\"{$leaderboard->getId()}\")'>View Rankings</button>";
echo "</div>";
}

echo "</div>";
}

echo "</div>";

} catch (Exception $e) {
echo "<div class='error'>Failed to load leaderboards. Please try again later.</div>";
error_log("Leaderboard selection error: " . $e->getMessage());
}
}

// Display on your page
displayLeaderboardSelection('your-game-id');

Leaderboard Management System

class LeaderboardManager {
private $moitribe;
private $gameId;
private $cache = [];
private $cacheExpiry = 300; // 5 minutes

public function __construct($moitribe, $gameId) {
$this->moitribe = $moitribe;
$this->gameId = $gameId;
}

public function getLeaderboards($useCache = true) {
$cacheKey = "leaderboards_{$this->gameId}";

// Check cache first
if ($useCache && isset($this->cache[$cacheKey])) {
$cached = $this->cache[$cacheKey];
if (time() - $cached['timestamp'] < $this->cacheExpiry) {
return $cached['data'];
}
}

try {
$leaderboards = $this->moitribe->leaderboardRequestsHandler->getLeaderboards($this->gameId);

// Cache the result
$this->cache[$cacheKey] = [
'data' => $leaderboards,
'timestamp' => time()
];

return $leaderboards;

} catch (Exception $e) {
error_log("Error getting leaderboards: " . $e->getMessage());
return [];
}
}

public function getLeaderboardById($leaderboardId) {
$leaderboards = $this->getLeaderboards();

foreach ($leaderboards as $leaderboard) {
if ($leaderboard->getId() === $leaderboardId) {
return $leaderboard;
}
}

return null;
}

public function getPopularLeaderboards($limit = 5) {
$leaderboards = $this->getLeaderboards();

// Sort by participant count
usort($leaderboards, function($a, $b) {
return $b->getParticipantCount() - $a->getParticipantCount();
});

return array_slice($leaderboards, 0, $limit);
}

public function getLeaderboardTypes() {
$leaderboards = $this->getLeaderboards();
$types = [];

foreach ($leaderboards as $leaderboard) {
$types[] = $leaderboard->getType();
}

return array_unique($types);
}

public function refreshCache() {
$cacheKey = "leaderboards_{$this->gameId}";
unset($this->cache[$cacheKey]);

return $this->getLeaderboards(false);
}
}

// Usage
$leaderboardManager = new LeaderboardManager($moitribe, 'your-game-id');

// Get all leaderboards (with caching)
$allLeaderboards = $leaderboardManager->getLeaderboards();
echo "Total leaderboards: " . count($allLeaderboards) . "\n";

// Get popular leaderboards
$popularLeaderboards = $leaderboardManager->getPopularLeaderboards(3);
echo "Popular leaderboards:\n";
foreach ($popularLeaderboards as $leaderboard) {
echo "- {$leaderboard->getName()} ({$leaderboard->getParticipantCount()} players)\n";
}

// Get available types
$types = $leaderboardManager->getLeaderboardTypes();
echo "Available types: " . implode(', ', $types) . "\n";

API Endpoint for Leaderboard List

function getLeaderboardsAPI() {
global $moitribe;

if ($_SERVER['REQUEST_METHOD'] !== 'GET') {
http_response_code(405);
echo json_encode(['error' => 'Method not allowed']);
return;
}

$gameId = $_GET['game_id'] ?? 'your-game-id';
$type = $_GET['type'] ?? null;
$limit = (int)($_GET['limit'] ?? 50);

try {
if (empty($gameId)) {
throw new InvalidArgumentException('Game ID is required');
}

$leaderboards = $moitribe->leaderboardRequestsHandler->getLeaderboards($gameId);

// Apply type filter
if ($type) {
$leaderboards = array_filter($leaderboards, function($leaderboard) use ($type) {
return $leaderboard->getType() === $type;
});
}

// Apply limit
if ($limit > 0) {
$leaderboards = array_slice($leaderboards, 0, $limit);
}

// Format response
$formattedLeaderboards = array_map(function($leaderboard) {
return [
'id' => $leaderboard->getId(),
'name' => $leaderboard->getName(),
'type' => $leaderboard->getType(),
'participant_count' => $leaderboard->getParticipantCount(),
'last_updated' => $leaderboard->getLastUpdated(),
'sort_order' => $leaderboard->getSortOrder(),
'update_frequency' => $leaderboard->getUpdateFrequency()
];
}, $leaderboards);

http_response_code(200);
echo json_encode([
'success' => true,
'data' => $formattedLeaderboards,
'count' => count($formattedLeaderboards)
]);

} catch (InvalidArgumentException $e) {
http_response_code(400);
echo json_encode(['success' => false, 'message' => $e->getMessage()]);
} catch (Exception $e) {
http_response_code(500);
echo json_encode(['success' => false, 'message' => 'Server error occurred']);
error_log("Leaderboard API error: " . $e->getMessage());
}
}

// Route handler
if (strpos($_SERVER['REQUEST_URI'], '/api/leaderboards') !== false) {
getLeaderboardsAPI();
}

Error Handling

Common Error Scenarios

  • Empty game ID - Invalid or missing game identifier
  • Invalid game ID - Game doesn't exist in Moitribe system
  • Access denied - No permission to view game leaderboards
  • Network issues - API communication problems

Error Handling Example

function safeGetLeaderboards($gameId) {
global $moitribe;

try {
if (empty($gameId)) {
throw new InvalidArgumentException("Game ID cannot be empty");
}

$leaderboards = $moitribe->leaderboardRequestsHandler->getLeaderboards($gameId);

return [
'success' => true,
'data' => $leaderboards,
'count' => count($leaderboards)
];

} catch (InvalidArgumentException $e) {
return [
'success' => false,
'error' => 'Invalid input: ' . $e->getMessage()
];
} catch (Exception $e) {
error_log("Leaderboard API error: " . $e->getMessage());
return [
'success' => false,
'error' => 'Failed to retrieve leaderboards'
];
}
}

// Usage
$result = safeGetLeaderboards('your-game-id');

if ($result['success']) {
echo "Found {$result['count']} leaderboards\n";
// Process leaderboards...
} else {
echo "Error: " . $result['error'] . "\n";
}

Best Practices

  1. Cache Leaderboard Data

    • Leaderboard lists don't change frequently
    • Cache for 5-15 minutes to improve performance
    • Invalidate cache when leaderboards are updated
  2. Handle Empty Results

    • Always check if returned array is empty
    • Provide user-friendly messages when no leaderboards are available
  3. Group and Filter

    • Group leaderboards by type for better organization
    • Provide filtering options for large lists
    • Show popular leaderboards prominently
  4. Display Metadata

    • Show participant counts to indicate popularity
    • Display last updated times
    • Include type information for context