Installation:
composer require binarythinking/lastfm-bundle:dev-master
Register the bundle in config/bundles.php (Symfony 4+):
return [
// ...
BinaryThinking\LastfmBundle\BinaryThinkingLastfmBundle::class => ['all' => true],
];
Configuration:
Add your Last.fm API key and secret in config/packages/binary_thinking_lastfm.yaml:
binary_thinking_lastfm:
client_apikey: "%env(LASTFM_API_KEY)%"
client_secret: "%env(LASTFM_SECRET)%"
First Use Case: Fetch an artist’s top tracks in a controller:
use BinaryThinking\LastfmBundle\Service\LastfmService;
public function showArtistTracks(LastfmService $lastfm, string $artistName)
{
$tracks = $lastfm->getArtistTopTracks($artistName);
return $this->render('artist/show.html.twig', ['tracks' => $tracks]);
}
Service Integration:
Inject LastfmService into controllers/services to interact with the API:
public function __construct(private LastfmService $lastfm) {}
Common Use Cases:
$artistInfo = $this->lastfm->getArtistInfo('Radiohead');
$similarArtists = $this->lastfm->getArtistSimilar($artistName);
$recentTracks = $this->lastfm->getUserRecentTracks('username');
$lovedTracks = $this->lastfm->getUserLovedTracks('username');
$topArtists = $this->lastfm->getTopArtists();
$topTracks = $this->lastfm->getTopTracks();
Pagination:
Handle paginated responses (e.g., getArtistTopTracks):
$tracks = $this->lastfm->getArtistTopTracks($artistName, 1, 5); // Page 1, 5 items
Geo Data: Fetch location-based charts:
$geoTopArtists = $this->lastfm->getTopArtistsByCountry('US');
Tagging: Explore tags for artists/albums:
$tags = $this->lastfm->getArtistTags('The Beatles');
Caching Responses: Cache API responses to reduce calls (e.g., using Symfony’s cache system):
$cache = $this->container->get('cache.app');
$cachedData = $cache->get('lastfm_artist_' . $artistName, function() use ($lastfm, $artistName) {
return $lastfm->getArtistInfo($artistName);
});
Event Listeners: Trigger actions on API updates (e.g., new tracks in a user’s library):
// In services.yaml
BinaryThinking\LastfmBundle\EventListener\LastfmListener:
tags:
- { name: kernel.event_listener, event: lastfm.track_updated, method: onTrackUpdated }
Form Integration: Use Last.fm data in forms (e.g., autocomplete for artists):
{{ form_widget(form.artist, {
'attr': {
'data-autocomplete-url': path('lastfm_artist_autocomplete')
}
}) }}
API Key Limits:
getUserRecentTracks in a loop without delays.Deprecated Methods:
getArtistBio) may return null or throw exceptions if the API endpoint is deprecated. Check the Last.fm API docs for updates.Error Handling:
try {
$data = $this->lastfm->getArtistInfo('InvalidArtist');
} catch (\Exception $e) {
// Handle gracefully (e.g., return 404)
}
Configuration Overrides:
binary_thinking_lastfm.yaml is in the correct location (config/packages/). For custom paths, override the bundle’s configuration:
# config/packages/binary_thinking_lastfm.yaml
binary_thinking_lastfm:
client_apikey: "%env(LASTFM_API_KEY)%"
client_secret: "%env(LASTFM_SECRET)%"
# Override default cache lifetime (in seconds)
cache_lifetime: 3600
Enable API Debugging:
Set the debug option in config to log API requests/responses:
binary_thinking_lastfm:
debug: true
Check logs in var/log/dev.log.
Validate API Key: Test your key with a simple endpoint first:
$this->lastfm->getArtistInfo('Radiohead'); // Should return data if key is valid
Handle Missing Data:
Some API responses may return empty arrays or null. Normalize data before use:
$tracks = $this->lastfm->getArtistTopTracks($artistName)['tracks'] ?? [];
Custom API Methods: Extend the service to add unsupported endpoints. Example:
// src/Service/ExtendedLastfmService.php
class ExtendedLastfmService extends LastfmService
{
public function getArtistEvents(string $artistName, int $limit = 10)
{
return $this->callApi('artist.getEvents', ['artist' => $artistName, 'limit' => $limit]);
}
}
Register as a service in services.yaml:
services:
App\Service\ExtendedLastfmService:
arguments:
$client: '@binary_thinking_lastfm.client'
tags: ['lastfm.service']
Override HTTP Client: Replace the default Guzzle client for custom behavior (e.g., retries):
# config/packages/binary_thinking_lastfm.yaml
binary_thinking_lastfm:
http_client:
timeout: 30
retries: 3
Add Twig Extensions: Create a custom Twig extension for reusable templates:
// src/Twig/LastfmExtension.php
class LastfmExtension extends \Twig\Extension\AbstractExtension
{
public function getFunctions()
{
return [
new \Twig\TwigFunction('lastfm_artist_image', [$this, 'getArtistImage']),
];
}
public function getArtistImage(string $artistName, string $size = 'medium'): string
{
$imageUrl = $this->lastfm->getArtistInfo($artistName)['image'] ?? [];
return $imageUrl[$size]['#text'] ?? '';
}
}
Register in services.yaml:
services:
App\Twig\LastfmExtension:
tags: ['twig.extension']
How can I help you explore Laravel packages today?