nucleos/lastfm
PHP wrapper for the Last.fm API. Install via Composer and use PSR-18/PSR-17 clients (e.g., Symfony HttpClient + Nyholm PSR-7) to authenticate, create sessions, and query services like charts and top tags.
Install the package:
composer require nucleos/lastfm symfony/http-client nyholm/psr7
symfony/http-client and nyholm/psr7 are required for PSR-18 HTTP client support.Initialize the connection:
use Nucleos\LastFm\Service\PsrClientConnection;
use Symfony\Contracts\HttpClient\HttpClientInterface;
$httpClient = \Symfony\Contracts\HttpClient\HttpClient::create();
$connection = new PsrClientConnection($httpClient);
First use case: Fetch top tags
use Nucleos\LastFm\Service\ChartService;
$chartService = new ChartService($connection);
$topTags = $chartService->getTopTags(10); // Returns top 10 tags
Authentication (if needed):
use Nucleos\LastFm\Service\AuthService;
$authService = new AuthService($connection);
$session = $authService->createSession('YOUR_API_TOKEN');
src/Service/ (e.g., ChartService, AuthService, ArtistService).src/Exception/ (e.g., LastFmException).src/Model/ (e.g., Tag, Artist, Track).ArtistService, TrackService).$artistService = new ArtistService($connection);
$topAlbums = $artistService->getTopAlbums('artist_name', 5);
AuthService to manage sessions:
$authService = new AuthService($connection);
$session = $authService->createSession($apiToken); // Authenticate
$authService->destroySession($sessionKey); // Logout
LastFmException:
try {
$tracks = $trackService->getTrackInfo('track_name');
} catch (LastFmException $e) {
Log::error('Last.fm API error: ' . $e->getMessage());
return response()->json(['error' => 'Failed to fetch track'], 500);
}
$cacheKey = "lastfm_top_tags_{$limit}";
$topTags = Cache::remember($cacheKey, now()->addHours(1), function () use ($chartService, $limit) {
return $chartService->getTopTags($limit);
});
PsrClientConnection and services in AppServiceProvider:
public function register()
{
$this->app->singleton(PsrClientConnection::class, function ($app) {
return new PsrClientConnection(HttpClient::create());
});
$this->app->bind(ChartService::class, function ($app) {
return new ChartService($app->make(PsrClientConnection::class));
});
}
$artistNames = ['Artist1', 'Artist2', 'Artist3'];
$artists = [];
foreach ($artistNames as $name) {
$artists[] = $artistService->getInfo($name);
}
API Routes:
Route::get('/lastfm/top-tags', function () {
$chartService = app(ChartService::class);
return response()->json($chartService->getTopTags(10));
});
Jobs for Async Tasks:
use Illuminate\Bus\Queueable;
use Nucleos\LastFm\Service\TrackService;
class FetchTrackInfoJob implements ShouldQueue
{
use Queueable;
public function handle(TrackService $trackService)
{
$info = $trackService->getTrackInfo('track_name');
// Process or store $info
}
}
PsrClientConnection in PHPUnit:
$mockClient = $this->createMock(HttpClientInterface::class);
$connection = new PsrClientConnection($mockClient);
$chartService = new ChartService($connection);
API Key Requirements
LastFmException.$connection->setApiKey('YOUR_API_KEY'); // Set globally or per request
Rate Limiting
Cache::forever("lastfm_{$cacheKey}", $data); // For static data
Deprecated Methods
album.getBuylinks) are removed by Last.fm. Check the limitations list before using.Session Management
LastFmException with 403 Forbidden to re-authenticate:
if ($e->getCode() === 403) {
$session = $authService->createSession($apiToken);
}
PSR-18 Client Quirks
HttpClient) is properly configured for redirects and timeouts:
$httpClient = HttpClient::create([
'timeout' => 10, // 10 seconds
'max_redirections' => 5,
]);
Enable Verbose Logging
PsrClientConnection to log raw responses:
$connection = new PsrClientConnection($httpClient, null, [
'debug' => true,
]);
Check Response Status Codes
LastFmException for HTTP status codes:
try {
$data = $service->someMethod();
} catch (LastFmException $e) {
if ($e->getCode() === 404) {
// Handle "not found"
}
}
Validate API Parameters
// Correct (uses package method):
$artistService->getTopAlbums('artist_name', 5);
// Avoid (manual API call):
$connection->request('artist.getTopAlbums', ['artist' => 'artist_name', 'limit' => 5]);
Custom HTTP Clients
PsrClientConnection to add middleware or retry logic:
class CustomConnection extends PsrClientConnection
{
public function __construct(HttpClientInterface $client)
{
parent::__construct($client, null, [
'retry' => true,
'retry_max_attempts' => 3,
]);
}
}
Response Transformers
class CustomChartService extends ChartService
{
public function getTopTags(int $limit): array
{
$response = parent::getTopTags($limit);
return array_map(fn($tag) => ['name' => $tag->getName(), 'url' => $tag->getUrl()], $response);
}
}
Event Listeners
LastFmResponse):
event(new LastFmResponse($responseData));
Webhook Integration
AuthService to validate Last.fm webhook signatures (if applicable):
$authService->validateWebhookSignature($rawBody, $signatureHeader);
config/services.php:
'lastfm' => [
'api_key' => env('LASTFM_API_KEY'),
],
$connection = new PsrClientConnection
How can I help you explore Laravel packages today?