Weave 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 Laravel Package

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.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. 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.
  2. Initialize the connection:

    use Nucleos\LastFm\Service\PsrClientConnection;
    use Symfony\Contracts\HttpClient\HttpClientInterface;
    
    $httpClient = \Symfony\Contracts\HttpClient\HttpClient::create();
    $connection = new PsrClientConnection($httpClient);
    
  3. First use case: Fetch top tags

    use Nucleos\LastFm\Service\ChartService;
    
    $chartService = new ChartService($connection);
    $topTags = $chartService->getTopTags(10); // Returns top 10 tags
    
  4. Authentication (if needed):

    use Nucleos\LastFm\Service\AuthService;
    
    $authService = new AuthService($connection);
    $session = $authService->createSession('YOUR_API_TOKEN');
    

Key Files to Reference

  • API Services: src/Service/ (e.g., ChartService, AuthService, ArtistService).
  • Exceptions: src/Exception/ (e.g., LastFmException).
  • Models: src/Model/ (e.g., Tag, Artist, Track).

Implementation Patterns

Core Workflows

1. Service-Based API Calls

  • Each API endpoint is wrapped in a dedicated service class (e.g., ArtistService, TrackService).
  • Example: Fetching an artist's top albums:
    $artistService = new ArtistService($connection);
    $topAlbums = $artistService->getTopAlbums('artist_name', 5);
    

2. Authentication Flow

  • Use AuthService to manage sessions:
    $authService = new AuthService($connection);
    $session = $authService->createSession($apiToken); // Authenticate
    $authService->destroySession($sessionKey);       // Logout
    

3. Error Handling

  • Wrap API calls in try-catch blocks to handle 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);
    }
    

4. Caching Responses

  • Cache frequent API calls (e.g., top charts) using Laravel's cache:
    $cacheKey = "lastfm_top_tags_{$limit}";
    $topTags = Cache::remember($cacheKey, now()->addHours(1), function () use ($chartService, $limit) {
        return $chartService->getTopTags($limit);
    });
    

5. Dependency Injection (Laravel)

  • Bind the 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));
        });
    }
    

6. Batch Processing

  • Use loops for bulk operations (e.g., fetching multiple artists):
    $artistNames = ['Artist1', 'Artist2', 'Artist3'];
    $artists = [];
    foreach ($artistNames as $name) {
        $artists[] = $artistService->getInfo($name);
    }
    

Integration Tips

Laravel Integration

  • 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
        }
    }
    

Testing

  • Mock the PsrClientConnection in PHPUnit:
    $mockClient = $this->createMock(HttpClientInterface::class);
    $connection = new PsrClientConnection($mockClient);
    $chartService = new ChartService($connection);
    

Gotchas and Tips

Pitfalls

  1. API Key Requirements

    • Always include your Last.fm API key in requests. Missing keys cause LastFmException.
    • Example:
      $connection->setApiKey('YOUR_API_KEY'); // Set globally or per request
      
  2. Rate Limiting

    • Last.fm enforces rate limits. Cache responses aggressively:
      Cache::forever("lastfm_{$cacheKey}", $data); // For static data
      
  3. Deprecated Methods

    • Some APIs (e.g., album.getBuylinks) are removed by Last.fm. Check the limitations list before using.
  4. Session Management

    • Sessions expire. Handle LastFmException with 403 Forbidden to re-authenticate:
      if ($e->getCode() === 403) {
          $session = $authService->createSession($apiToken);
      }
      
  5. PSR-18 Client Quirks

    • Ensure your HTTP client (e.g., Symfony's HttpClient) is properly configured for redirects and timeouts:
      $httpClient = HttpClient::create([
          'timeout' => 10, // 10 seconds
          'max_redirections' => 5,
      ]);
      

Debugging Tips

  1. Enable Verbose Logging

    • Configure the PsrClientConnection to log raw responses:
      $connection = new PsrClientConnection($httpClient, null, [
          'debug' => true,
      ]);
      
  2. Check Response Status Codes

    • Inspect LastFmException for HTTP status codes:
      try {
          $data = $service->someMethod();
      } catch (LastFmException $e) {
          if ($e->getCode() === 404) {
              // Handle "not found"
          }
      }
      
  3. Validate API Parameters

    • Last.fm is strict about parameter names/casing. Use the package's methods instead of raw API calls:
      // Correct (uses package method):
      $artistService->getTopAlbums('artist_name', 5);
      
      // Avoid (manual API call):
      $connection->request('artist.getTopAlbums', ['artist' => 'artist_name', 'limit' => 5]);
      

Extension Points

  1. Custom HTTP Clients

    • Extend 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,
              ]);
          }
      }
      
  2. Response Transformers

    • Override response parsing in services. Example:
      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);
          }
      }
      
  3. Event Listeners

    • Dispatch events for API responses (e.g., LastFmResponse):
      event(new LastFmResponse($responseData));
      
  4. Webhook Integration

    • Use the AuthService to validate Last.fm webhook signatures (if applicable):
      $authService->validateWebhookSignature($rawBody, $signatureHeader);
      

Configuration Quirks

  1. Default API Key
    • Set a default API key in config/services.php:
      'lastfm' => [
          'api_key' => env('LASTFM_API_KEY'),
      ],
      
    • Then inject it into the connection:
      $connection = new PsrClientConnection
      
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.
roundly-consulting/kubernetes-api-for-laravel
roundly-consulting/plausible-for-laravel
gvp/gvp-laravel-template
metasyncsite/laravel-metasync-client
roundly-consulting/onboarding-for-laravel
andydefer/laravel-notification
adachsoft/cli-process-tester
jhaskell13/laraflow
sebastienheyd/boilerplate-media-manager
ccast/tagixo-primix
pretendtrue/laravel-builder
sawmainek/laravel-scout-tntsearch-driver
tomshaw/laravel-calendar-table
dibakar/laravel-ownership
steadrun/laravel-monitor
labyrinthe/connect-laravel
elmogy/layan
drewdan/sentinel-client
dskripchenko/laravel-llm
fatryst/nuonuo