Get Player Friends
The get friends method retrieves a player's friends list, including their online status and basic profile information. This is useful for social features and friend management.
Overview
The getFriends method:
- Retrieves player's friends list
- Supports pagination for large friends lists
- Returns friend profiles with online status
- Provides filtering options
Method Signature
public function getFriends(string $playerid, int $page, int $maxResults): array
Parameters
Required Parameters
playerid(String) - The Player ID to retrieve friends forpage(int) - Page number for paginationmaxResults(int) - Maximum number of friends per page
Return Value
Returns an array containing:
- Friends list - Array of
Playerobjects representing friends - Pagination info - Total friends count and current page
- Online status - Friend availability status
- Profile data - Basic friend information
Basic Usage
Get Player Friends List
use Veniso\Moitribe\Sdk\modules\classes\MoitribeApi;
$moitribe = new MoitribeApi([
'gameid' => 'your-game-id',
'channelid' => 'your-channel-id',
'playerid' => 'player-123'
]);
try {
$friends = $moitribe->profRequestsHandler->getFriends(
'player-123',
0, // first page
20 // 20 friends per page
);
echo "Friends List:\n";
echo "Total friends: " . count($friends) . "\n\n";
foreach ($friends as $friend) {
echo "- " . $friend->getName() . " (ID: " . $friend->getId() . ")\n";
echo " Status: " . $friend->getOnlineStatus() . "\n";
echo " Level: " . $friend->getLevel() . "\n\n";
}
} catch (Exception $e) {
echo "Error: " . $e->getMessage() . "\n";
}
Paginated Friends List
function getFriendsPaginated($playerId, $page = 0, $pageSize = 25) {
global $moitribe;
try {
$friends = $moitribe->profRequestsHandler->getFriends(
$playerId,
$page,
$pageSize
);
return [
'success' => true,
'friends' => $friends,
'current_page' => $page,
'page_size' => $pageSize,
'total_friends' => count($friends),
'has_more' => count($friends) >= $pageSize
];
} catch (Exception $e) {
error_log("Friends list error: " . $e->getMessage());
return [
'success' => false,
'error' => 'Failed to retrieve friends list'
];
}
}
// Usage
$page = isset($_GET['page']) ? (int)$_GET['page'] : 0;
$result = getFriendsPaginated('player-123', $page);
if ($result['success']) {
echo "Page " . ($result['current_page'] + 1) . " of friends\n";
echo "Showing " . count($result['friends']) . " friends\n";
foreach ($result['friends'] as $friend) {
echo "- " . $friend->getName() . "\n";
}
if ($result['has_more']) {
echo "<a href='?page=" . ($result['current_page'] + 1) . "'>Load More</a>";
}
} else {
echo "Error: " . $result['error'] . "\n";
}
Integration Examples
Friends Management System
class FriendsManager {
private $moitribe;
private $gameId;
private $cache = [];
private $cacheExpiry = 300; // 5 minutes
public function __construct($moitribe, $gameId) {
$this->moitribe = $moitribe;
$this->gameId = $gameId;
}
public function getPlayerFriends($playerId, $options = []) {
try {
$cacheKey = "friends_{$playerId}";
// Check cache first
if (isset($this->cache[$cacheKey])) {
$cached = $this->cache[$cacheKey];
if (time() - $cached['timestamp'] < $this->cacheExpiry) {
return $cached['data'];
}
}
// Get friends with pagination
$page = $options['page'] ?? 0;
$pageSize = $options['page_size'] ?? 20;
$includeOffline = $options['include_offline'] ?? true;
$allFriends = $this->moitribe->profRequestsHandler->getFriends(
$playerId,
$page,
$pageSize
);
// Filter by online status if requested
if (!$includeOffline) {
$allFriends = array_filter($allFriends, function($friend) {
return $friend->getOnlineStatus() === 'online';
});
}
// Cache the result
$this->cache[$cacheKey] = [
'data' => $allFriends,
'timestamp' => time()
];
return [
'success' => true,
'friends' => $allFriends,
'page' => $page,
'page_size' => $pageSize,
'total_count' => count($allFriends)
];
} catch (Exception $e) {
error_log("Friends manager error: " . $e->getMessage());
return [
'success' => false,
'error' => 'Failed to retrieve friends list'
];
}
}
public function getOnlineFriends($playerId) {
return $this->getPlayerFriends($playerId, [
'include_offline' => false,
'page_size' => 50
]);
}
public function searchFriends($playerId, $searchTerm) {
$friends = $this->getPlayerFriends($playerId, ['page_size' => 100]);
if (empty($searchTerm)) {
return $friends;
}
$searchTerm = strtolower($searchTerm);
$matchedFriends = array_filter($friends['friends'], function($friend) use ($searchTerm) {
$name = strtolower($friend->getName());
return strpos($name, $searchTerm) !== false;
});
return [
'success' => true,
'friends' => array_values($matchedFriends),
'search_term' => $searchTerm,
'total_matches' => count($matchedFriends)
];
}
public function getFriendsByLevel($playerId, $minLevel = null, $maxLevel = null) {
$friends = $this->getPlayerFriends($playerId)['friends'];
$filteredFriends = $friends;
if ($minLevel !== null) {
$filteredFriends = array_filter($filteredFriends, function($friend) use ($minLevel) {
return $friend->getLevel() >= $minLevel;
});
}
if ($maxLevel !== null) {
$filteredFriends = array_filter($filteredFriends, function($friend) use ($maxLevel) {
return $friend->getLevel() <= $maxLevel;
});
}
return [
'success' => true,
'friends' => array_values($filteredFriends),
'level_filter' => [
'min_level' => $minLevel,
'max_level' => $maxLevel
],
'total_count' => count($filteredFriends)
];
}
public function refreshCache($playerId) {
$cacheKey = "friends_{$playerId}";
unset($this->cache[$cacheKey]);
return $this->getPlayerFriends($playerId);
}
}
// Usage
$friendsManager = new FriendsManager($moitribe, 'your-game-id');
// Get all friends
$allFriends = $friendsManager->getPlayerFriends('player-123');
echo "Total friends: " . $allFriends['total_count'] . "\n";
// Get only online friends
$onlineFriends = $friendsManager->getOnlineFriends('player-123');
echo "Online friends: " . count($onlineFriends['friends']) . "\n";
// Search friends
$searchResult = $friendsManager->searchFriends('player-123', 'john');
echo "Found " . $searchResult['total_matches'] . " friends matching '{$searchResult['search_term']}'\n";
// Get friends by level
$highLevelFriends = $friendsManager->getFriendsByLevel('player-123', 50, 100);
echo "High level friends: " . $highLevelFriends['total_count'] . "\n";
Web Friends API Handler
function getFriendsAPI() {
global $moitribe;
if ($_SERVER['REQUEST_METHOD'] !== 'GET') {
http_response_code(405);
echo json_encode(['error' => 'Method not allowed']);
return;
}
$playerId = $_GET['player_id'] ?? '';
$page = (int)($_GET['page'] ?? 0);
$pageSize = (int)($_GET['page_size'] ?? 20);
$includeOffline = filter_var($_GET['include_offline'] ?? true, FILTER_VALIDATE_BOOLEAN);
try {
if (empty($playerId)) {
throw new InvalidArgumentException('Player ID is required');
}
if ($page < 0 || $pageSize < 1 || $pageSize > 100) {
throw new InvalidArgumentException('Invalid pagination parameters');
}
$friends = $moitribe->profRequestsHandler->getFriends($playerId, $page, $pageSize);
// Format response
$formattedFriends = array_map(function($friend) {
return [
'id' => $friend->getId(),
'name' => $friend->getName(),
'level' => $friend->getLevel(),
'online_status' => $friend->getOnlineStatus(),
'last_seen' => $friend->getLastSeen(),
'avatar_url' => $friend->getAvatarUrl(),
'is_online' => $friend->getOnlineStatus() === 'online'
];
}, $friends);
http_response_code(200);
echo json_encode([
'success' => true,
'data' => $formattedFriends,
'pagination' => [
'current_page' => $page,
'page_size' => $pageSize,
'total_friends' => count($friends),
'has_more' => count($friends) >= $pageSize
]
]);
} 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("Friends API error: " . $e->getMessage());
}
}
// Route handler
if (strpos($_SERVER['REQUEST_URI'], '/api/friends') !== false) {
getFriendsAPI();
}
Error Handling
Common Error Scenarios
- Invalid player ID - Player doesn't exist
- Pagination errors - Invalid page or page size parameters
- Access denied - No permission to view friends list
- Network issues - API communication problems
Error Handling Example
function safeGetFriends($playerId, $page = 0, $pageSize = 20) {
global $moitribe;
try {
if (empty($playerId)) {
throw new InvalidArgumentException("Player ID is required");
}
if ($page < 0 || $pageSize < 1 || $pageSize > 100) {
throw new InvalidArgumentException("Invalid pagination parameters");
}
$friends = $moitribe->profRequestsHandler->getFriends($playerId, $page, $pageSize);
return [
'success' => true,
'friends' => $friends,
'page' => $page,
'page_size' => $pageSize,
'total_count' => count($friends)
];
} catch (InvalidArgumentException $e) {
return [
'success' => false,
'error' => 'Invalid input: ' . $e->getMessage()
];
} catch (Exception $e) {
error_log("Friends API error: " . $e->getMessage());
return [
'success' => false,
'error' => 'Failed to retrieve friends list'
];
}
}
Best Practices
-
Implement Pagination
- Friends lists can become very large
- Use reasonable page sizes (20-50 friends)
- Provide navigation between pages
-
Cache Friends Data
- Friends lists don't change frequently
- Cache for 5-15 minutes to improve performance
- Implement cache invalidation when friends are added/removed
-
Filter and Search
- Provide online/offline filtering options
- Implement search functionality for large friends lists
- Allow filtering by level or other criteria
-
Protect Privacy
- Only show friends lists to authenticated players
- Consider privacy settings and friend visibility
- Limit sensitive information exposure
Related Methods
- Force Login with Unique ID - Authenticate players before accessing friends
- Update Player Profile - Manage player information
- Get Multiple Players - Get specific player profiles