Install the Bundle
composer require nucleos/lastfm-bundle
Enable the bundle in config/bundles.php:
return [
// ...
Nucleos\LastFmBundle\NucleosLastFmBundle::class => ['all' => true],
];
Configure API Key
Add your Last.fm API key to config/packages/nucleos_lastfm.yaml:
nucleos_lastfm:
api_key: '%env(LASTFM_API_KEY)%'
Store the key in .env:
LASTFM_API_KEY=your_api_key_here
First Use Case: Fetching Artist Info
Inject the LastFmClient service and call methods:
use Nucleos\LastFmBundle\Client\LastFmClientInterface;
class ArtistController extends AbstractController
{
public function show(LastFmClientInterface $client): Response
{
$artist = $client->getArtist('Arctic Monkeys');
return $this->json($artist);
}
}
LastFmClientInterface (main interface for API calls).Artist, Track, Album, User, etc. (DTOs for responses).LastFmException (handle API errors gracefully).Fetching Data Use the client’s fluent methods for common queries:
// Get top tracks for an artist
$tracks = $client->getArtistTopTracks('The Weeknd');
// Get user's recent tracks
$recentTracks = $client->getUserRecentTracks('username');
Search Functionality
// Search for artists
$results = $client->searchArtists('Queen');
// Search for tracks
$results = $client->searchTracks('Bohemian Rhapsody');
User-Specific Data
// Get user's loved tracks
$lovedTracks = $client->getUserLovedTracks('username');
// Get user's top albums
$topAlbums = $client->getUserTopAlbums('username');
Chart Data
// Get top artists globally
$topArtists = $client->getTopArtists();
// Get top tracks in a country
$topTracks = $client->getTopTracks('US');
Caching Responses
Decorate the LastFmClientInterface to cache responses (e.g., with Symfony’s CacheInterface):
$client = new CachedLastFmClient(
$originalClient,
$cache,
3600 // Cache for 1 hour
);
Event-Driven Updates Use Symfony’s event dispatcher to trigger actions when data changes (e.g., update a user’s "now playing" status):
$client->getUserNowPlaying('username')->then(
fn($track) => $this->eventDispatcher->dispatch(new TrackUpdatedEvent($track))
);
Background Processing Offload API calls to a message queue (e.g., Symfony Messenger) for heavy operations like batch updates:
$this->messageBus->dispatch(new FetchArtistTopTracksMessage('ArtistName'));
Form Integration Use the bundle’s entities in forms for user input (e.g., artist/track selection):
$builder->add('artist', EntityType::class, [
'class' => Artist::class,
'query_builder' => fn($er) => $er->search('Arctic'),
]);
Rate Limiting
LastFmException on failures.API Key Validation
LastFmException.$client->ping(); // Throws exception if key is invalid
Deprecated Endpoints
Pagination Handling
getUserTopTracks) return paginated results. The bundle returns only the first page by default.page and perPage parameters:
$tracks = $client->getUserTopTracks('username', page: 2, perPage: 50);
Async/Await Quirks
HttpClient under the hood, which supports async requests. However, the public methods are synchronous by default.HttpClient directly for async calls:
$response = $client->getHttpClient()->request('GET', '/artist/getInfo', [
'query' => ['artist' => 'Arctic Monkeys', 'api_key' => $key],
]);
Enable Verbose Logging Configure the bundle to log raw API responses:
nucleos_lastfm:
debug: true
Check logs in var/log/dev.log for detailed request/response data.
Mocking the Client for Tests Use PHPUnit’s mocking to isolate tests:
$mockClient = $this->createMock(LastFmClientInterface::class);
$mockClient->method('getArtist')->willReturn(new Artist('Test Artist'));
$this->container->set(LastFmClientInterface::class, $mockClient);
Handling Malformed Responses
Last.fm’s API sometimes returns unexpected data. Override the bundle’s LastFmResponseFactory to sanitize responses:
class CustomResponseFactory extends LastFmResponseFactory
{
public function createFromResponse(ResponseInterface $response): array
{
$data = parent::createFromResponse($response);
return $this->sanitizeData($data);
}
}
Register it in services.yaml:
Nucleos\LastFmBundle\Client\LastFmClient:
arguments:
$responseFactory: '@app.custom_response_factory'
Custom Endpoints
Extend the LastFmClient to add unsupported endpoints:
class ExtendedLastFmClient extends LastFmClient
{
public function getCustomEndpoint(array $params): array
{
return $this->request('GET', '/custom/endpoint', $params);
}
}
Response Transformers
Modify how responses are converted to entities. Override the LastFmResponseFactory:
class CustomResponseFactory extends LastFmResponseFactory
{
protected function createArtist(array $data): Artist
{
$artist = parent::createArtist($data);
$artist->setCustomField($data['custom_field']);
return $artist;
}
}
Authentication
The bundle supports Last.fm’s auth system. Extend the LastFmAuthenticator:
class CustomAuthenticator extends LastFmAuthenticator
{
public function getAuthToken(string $username, string $password): string
{
// Custom auth logic
}
}
Event Listeners
Listen for API events (e.g., LastFmResponseEvent) to log or transform data:
class LastFmLoggerSubscriber implements EventSubscriberInterface
{
public static function getSubscribedEvents(): array
{
return [
LastFmEvents::RESPONSE => 'onResponse',
];
}
public function onResponse(LastFmResponseEvent $event): void
{
$this->logger->info('Last.fm API Response', ['data' => $event->getData()]);
}
}
How can I help you explore Laravel packages today?