Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Lastfm Bundle Laravel Package

core23/lastfm-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Install the Bundle

    composer require nucleos/lastfm-bundle
    

    Enable the bundle in config/bundles.php:

    return [
        // ...
        Nucleos\LastFmBundle\NucleosLastFmBundle::class => ['all' => true],
    ];
    
  2. 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
    
  3. 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);
        }
    }
    

Key Entry Points

  • Client Services: LastFmClientInterface (main interface for API calls).
  • Entities: Artist, Track, Album, User, etc. (DTOs for responses).
  • Exceptions: LastFmException (handle API errors gracefully).

Implementation Patterns

Common Workflows

  1. 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');
    
  2. Search Functionality

    // Search for artists
    $results = $client->searchArtists('Queen');
    
    // Search for tracks
    $results = $client->searchTracks('Bohemian Rhapsody');
    
  3. User-Specific Data

    // Get user's loved tracks
    $lovedTracks = $client->getUserLovedTracks('username');
    
    // Get user's top albums
    $topAlbums = $client->getUserTopAlbums('username');
    
  4. Chart Data

    // Get top artists globally
    $topArtists = $client->getTopArtists();
    
    // Get top tracks in a country
    $topTracks = $client->getTopTracks('US');
    

Integration Tips

  • 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'),
    ]);
    

Gotchas and Tips

Pitfalls

  1. Rate Limiting

    • Last.fm enforces strict rate limits. The bundle throws LastFmException on failures.
    • Fix: Implement exponential backoff or use a queue system to distribute requests.
  2. API Key Validation

    • The bundle validates the API key on first use. If invalid, it throws LastFmException.
    • Fix: Test the key early in development:
      $client->ping(); // Throws exception if key is invalid
      
  3. Deprecated Endpoints

    • Last.fm occasionally deprecates endpoints. Check the official API docs for updates.
    • Fix: Monitor the bundle’s changelog or fork the bundle if needed.
  4. Pagination Handling

    • Some endpoints (e.g., getUserTopTracks) return paginated results. The bundle returns only the first page by default.
    • Fix: Use the page and perPage parameters:
      $tracks = $client->getUserTopTracks('username', page: 2, perPage: 50);
      
  5. Async/Await Quirks

    • The bundle uses Symfony’s HttpClient under the hood, which supports async requests. However, the public methods are synchronous by default.
    • Fix: Use HttpClient directly for async calls:
      $response = $client->getHttpClient()->request('GET', '/artist/getInfo', [
          'query' => ['artist' => 'Arctic Monkeys', 'api_key' => $key],
      ]);
      

Debugging Tips

  1. 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.

  2. 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);
    
  3. 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'
    

Extension Points

  1. 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);
        }
    }
    
  2. 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;
        }
    }
    
  3. 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
        }
    }
    
  4. 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()]);
        }
    }
    
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
babenkoivan/elastic-client
innmind/static-analysis
innmind/coding-standard
datacore/hub-sdk
alengo/sulu-http-cache-bundle
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony
develia/geo-bundle
dreamzy/livewire-charts
touchestate-sdk/php-sdk
22h/doctrine-garbage-collection-bundle
imbo/imbo-coding-standard
visualbuilder/filament-lottie
servicioslineaonce/starter-kit
atomcoder/laravel-reorderable
irajul/filament-shadcn-theme
agtp/agtp-php
agtp/mod-php
centraldesktop/protobuf-php