Get Multiple Players
The get players method allows you to retrieve multiple player profiles at once, which is useful for displaying player information in leaderboards, tournaments, or social features.
Overview
The getPlayers method:
- Retrieves multiple player profiles in a single request
- Supports batch processing for efficiency
- Returns player profile information
- Handles large player lists efficiently
Method Signature
public function getPlayers(array $playerids): array
Parameters
Required Parameters
playerids(Array) - Array of player IDs to retrieve profiles for- Must be an array of valid player ID strings
- Maximum recommended: 50-100 player IDs per request
Return Value
Returns an array containing:
- Player profiles - Array of
Playerobjects for found players - Missing players - Player IDs that couldn't be found
- Error information - Details about any failed lookups
Basic Usage
Get Multiple Player Profiles
use Veniso\Moitribe\Sdk\modules\classes\MoitribeApi;
$moitribe = new MoitribeApi([
'gameid' => 'your-game-id',
'channelid' => 'your-channel-id',
'playerid' => 'player-123'
]);
try {
$playerIds = ['player-123', 'player-456', 'player-789', 'player-101'];
$players = $moitribe->profRequestsHandler->getPlayers($playerIds);
echo "Retrieved " . count($players) . " player profiles:\n";
foreach ($players as $player) {
echo "- " . $player->getName() . " (ID: " . $player->getId() . ")\n";
echo " Level: " . $player->getLevel() . "\n";
echo " Status: " . $player->getStatus() . "\n";
echo " Avatar: " . $player->getAvatarUrl() . "\n\n";
}
} catch (Exception $e) {
echo "Error: " . $e->getMessage() . "\n";
}
Batch Player Processing
function processBatchPlayerProfiles($playerIds, $batchSize = 50) {
global $moitribe;
try {
$allPlayers = [];
$batches = array_chunk($playerIds, $batchSize);
foreach ($batches as $batchIndex => $batch) {
echo "Processing batch " . ($batchIndex + 1) . " of " . count($batches) . "\n";
$batchPlayers = $moitribe->profRequestsHandler->getPlayers($batch);
// Process each player in the batch
foreach ($batchPlayers as $player) {
$allPlayers[$player->getId()] = $player;
// Additional processing
$playerData = [
'id' => $player->getId(),
'name' => $player->getName(),
'level' => $player->getLevel(),
'experience' => $player->getExperience(),
'achievements' => $player->getAchievements(),
'last_active' => $player->getLastActive()
];
// Store or process player data
storePlayerData($playerData);
}
// Small delay to avoid overwhelming API
usleep(100000); // 0.1 seconds
}
return [
'success' => true,
'total_players' => count($allPlayers),
'processed_batches' => count($batches),
'players' => $allPlayers
];
} catch (Exception $e) {
error_log("Batch player processing error: " . $e->getMessage());
return [
'success' => false,
'error' => $e->getMessage()
];
}
}
function storePlayerData($playerData) {
// Store player data in your database
error_log("Storing player data: " . json_encode($playerData));
}
// Usage
$playerIds = [
'player-1', 'player-2', 'player-3', 'player-4', 'player-5',
'player-6', 'player-7', 'player-8', 'player-9', 'player-10',
// ... more player IDs
];
$result = processBatchPlayerProfiles($playerIds, 25);
if ($result['success']) {
echo "Successfully processed {$result['total_players']} players\n";
echo "Used {$result['processed_batches']} batches\n";
} else {
echo "Error: " . $result['error'] . "\n";
}
Integration Examples
Player Profile Cache System
class PlayerProfileCache {
private $moitribe;
private $cache = [];
private $cacheExpiry = 600; // 10 minutes
public function __construct($moitribe) {
$this->moitribe = $moitribe;
}
public function getPlayers($playerIds, $useCache = true) {
$cacheKey = 'players_' . md5(implode(',', $playerIds));
// Check cache first
if ($useCache && isset($this->cache[$cacheKey])) {
$cached = $this->cache[$cacheKey];
if (time() - $cached['timestamp'] < $this->cacheExpiry) {
return $cached['data'];
}
}
try {
$players = $this->moitribe->profRequestsHandler->getPlayers($playerIds);
// Cache the result
$this->cache[$cacheKey] = [
'data' => $players,
'timestamp' => time()
];
return $players;
} catch (Exception $e) {
error_log("Player profile cache error: " . $e->getMessage());
return [];
}
}
public function getPlayer($playerId, $useCache = true) {
return $this->getPlayers([$playerId], $useCache);
}
public function invalidateCache($playerIds = null) {
if ($playerIds === null) {
// Clear all player cache
$this->cache = [];
} else {
// Clear specific players from cache
foreach ($playerIds as $playerId) {
$cacheKey = 'players_' . md5($playerId);
unset($this->cache[$cacheKey]);
}
}
}
public function getCacheStats() {
$totalCached = 0;
$expiredCount = 0;
foreach ($this->cache as $key => $data) {
$totalCached++;
if (time() - $data['timestamp'] >= $this->cacheExpiry) {
$expiredCount++;
}
}
return [
'total_cached_entries' => $totalCached,
'expired_entries' => $expiredCount,
'cache_hit_ratio' => $totalCached > 0 ? (($totalCached - $expiredCount) / $totalCached) * 100 : 0
];
}
}
// Usage
$playerCache = new PlayerProfileCache($moitribe);
// Get single player (with caching)
$player = $playerCache->getPlayer('player-123');
// Get multiple players (with caching)
$players = $playerCache->getPlayers(['player-123', 'player-456', 'player-789']);
// Invalidate cache for specific players
$playerCache->invalidateCache(['player-123', 'player-456']);
// Get cache statistics
$stats = $playerCache->getCacheStats();
echo "Cache hit ratio: " . $stats['cache_hit_ratio'] . "%\n";
Web API for Multiple Players
function getMultiplePlayersAPI() {
global $moitribe;
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
http_response_code(405);
echo json_encode(['error' => 'Method not allowed']);
return;
}
$input = json_decode(file_get_contents('php://input'), true);
if (!isset($input['player_ids']) || !is_array($input['player_ids'])) {
http_response_code(400);
echo json_encode(['error' => 'player_ids array is required']);
return;
}
$playerIds = $input['player_ids'];
// Validate player IDs
if (count($playerIds) > 100) {
http_response_code(400);
echo json_encode(['error' => 'Maximum 100 player IDs allowed per request']);
return;
}
foreach ($playerIds as $playerId) {
if (empty($playerId) || !is_string($playerId)) {
http_response_code(400);
echo json_encode(['error' => 'Invalid player ID format']);
return;
}
}
try {
$players = $moitribe->profRequestsHandler->getPlayers($playerIds);
// Format response
$formattedPlayers = array_map(function($player) {
return [
'id' => $player->getId(),
'name' => $player->getName(),
'level' => $player->getLevel(),
'experience' => $player->getExperience(),
'avatar_url' => $player->getAvatarUrl(),
'status' => $player->getStatus(),
'last_active' => $player->getLastActive(),
'achievements' => $player->getAchievements(),
'friends_count' => $player->getFriendsCount(),
'created_at' => $player->getCreatedAt(),
'last_login' => $player->getLastLogin()
];
}, $players);
http_response_code(200);
echo json_encode([
'success' => true,
'data' => $formattedPlayers,
'count' => count($formattedPlayers)
]);
} catch (Exception $e) {
http_response_code(500);
echo json_encode(['success' => false, 'message' => 'Server error occurred']);
error_log("Multiple players API error: " . $e->getMessage());
}
}
// Route handler
if (strpos($_SERVER['REQUEST_URI'], '/api/players/multiple') !== false) {
getMultiplePlayersAPI();
}
Error Handling
Common Error Scenarios
- Empty player IDs array - No player IDs provided
- Invalid player ID format - Non-string or empty player IDs
- Too many player IDs - Exceeds API limits
- Invalid player IDs - Player IDs don't exist
- Network issues - API communication problems
Error Handling Example
function safeGetPlayers($playerIds) {
global $moitribe;
try {
if (empty($playerIds) || !is_array($playerIds)) {
throw new InvalidArgumentException("Player IDs array is required");
}
if (count($playerIds) > 100) {
throw new InvalidArgumentException("Maximum 100 player IDs allowed per request");
}
// Validate each player ID
foreach ($playerIds as $playerId) {
if (empty($playerId) || !is_string($playerId)) {
throw new InvalidArgumentException("Invalid player ID format: $playerId");
}
}
$players = $moitribe->profRequestsHandler->getPlayers($playerIds);
return [
'success' => true,
'players' => $players,
'requested_count' => count($playerIds),
'found_count' => count($players)
];
} catch (InvalidArgumentException $e) {
return [
'success' => false,
'error' => 'Invalid input: ' . $e->getMessage()
];
} catch (Exception $e) {
error_log("Multiple players API error: " . $e->getMessage());
return [
'success' => false,
'error' => 'Failed to retrieve player profiles'
];
}
}
// Usage
$playerIds = ['player-123', 'player-456', 'player-789'];
$result = safeGetPlayers($playerIds);
if ($result['success']) {
echo "Found {$result['found_count']} of {$result['requested_count']} requested players\n";
// Process players...
} else {
echo "Error: " . $result['error'] . "\n";
}
Best Practices
-
Batch Processing
- Group player IDs into reasonable batches (25-50 players)
- Add delays between batches to avoid overwhelming API
- Process large player lists asynchronously when possible
-
Implement Caching
- Cache player profiles for 5-15 minutes
- Use cache keys based on player ID lists
- Implement cache invalidation strategies
-
Validate Input Data
- Ensure player IDs are valid strings
- Limit number of player IDs per request
- Handle malformed input gracefully
-
Handle Missing Players
- Some player IDs may not exist or be invalid
- Return partial results with found/missing player information
- Log missing players for debugging
Related Methods
- Force Login with Unique ID - Authenticate individual players
- Update Player Profile - Manage player information
- Get Player Friends - Get player's friends list