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

calliostro/lastfm-client

Lightweight Last.fm API client for PHP 8.1+ with clean, modern methods for artists, albums, tracks, search, and charts. Uses Guzzle and supports API-key access for all calls plus session authentication for write actions like scrobbling and loving tracks.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Install the package:
    composer require calliostro/lastfm-client
    
  2. Register your app at Last.fm API Account to get credentials.
  3. Initialize the client (read-only):
    use Calliostro\LastFm\LastFmClientFactory;
    
    $lastfm = LastFmClientFactory::createWithApiKey('your-api-key', 'your-secret');
    

First Use Case: Fetch Artist Info

$artist = $lastfm->getArtistInfo('Billie Eilish');
dd($artist); // Returns structured artist data

First Use Case: Search Tracks

$tracks = $lastfm->searchTracks(track: 'Anti-Hero', artist: 'Taylor Swift', limit: 5);
dd($tracks);

Implementation Patterns

Core Workflow: Read-Only Operations

  1. Initialize client with API key/secret:
    $lastfm = LastFmClientFactory::createWithApiKey('key', 'secret');
    
  2. Call methods using natural language:
    $artist = $lastfm->getArtistInfo('Artist Name');
    $tracks = $lastfm->getArtistTopTracks('Artist Name', limit: 10);
    
  3. Handle responses (always returns associative arrays):
    if (isset($artist['artist'])) {
        echo $artist['artist']['name'];
    }
    

Authentication Workflow: User-Specific Operations

  1. Session-based auth (for scrobbling, user data):
    $lastfm = LastFmClientFactory::createWithSession('key', 'secret', 'session-key');
    
  2. Mobile auth (for username/password):
    $lastfm = LastFmClientFactory::createWithMobileAuth('key', 'secret', 'username', 'password');
    
  3. Scrobble tracks:
    $lastfm->scrobbleTrack(
        artist: 'Artist',
        track: 'Track',
        timestamp: time()
    );
    

Integration with Laravel

  1. Service Provider Binding:
    // app/Providers/AppServiceProvider.php
    public function register()
    {
        $this->app->singleton(LastFmClient::class, function ($app) {
            return LastFmClientFactory::createWithApiKey(
                config('services.lastfm.key'),
                config('services.lastfm.secret')
            );
        });
    }
    
  2. Config File (config/services.php):
    'lastfm' => [
        'key' => env('LASTFM_API_KEY'),
        'secret' => env('LASTFM_API_SECRET'),
    ],
    
  3. Dependency Injection:
    public function __construct(private LastFmClient $lastfm) {}
    

Batch Operations

// Fetch top artists for multiple countries
$countries = ['US', 'UK', 'DE'];
$charts = collect($countries)->map(fn($country) =>
    $lastfm->getTopArtistsByCountry($country)
);

Error Handling

try {
    $artist = $lastfm->getArtistInfo('Nonexistent Artist');
} catch (LastFmException $e) {
    if ($e->getCode() === 1) { // Invalid artist
        // Handle gracefully
    }
}

Gotchas and Tips

Common Pitfalls

  1. Missing Authentication:

    • Error: Error Code 6 → Missing required parameter
    • Fix: Ensure createWithSession() for user-specific operations.
    • Tip: Use try-catch with LastFmException for clear error messages.
  2. Rate Limiting:

    • Last.fm enforces 300 calls/10 minutes per API key.
    • Solution: Implement Guzzle middleware for retries:
      $handler = HandlerStack::create();
      $handler->push(Middleware::retry(
          fn ($retries) => $retries < 3,
          fn ($retries) => 1000 * 2 ** $retries
      ));
      $lastfm = LastFmClientFactory::createWithApiKey('key', 'secret', ['handler' => $handler]);
      
  3. Parameter Validation:

    • Gotcha: Null values are omitted (Last.fm API requirement).
    • Tip: Explicitly pass null for optional parameters:
      $lastfm->searchTracks(track: 'Track', artist: null); // Forces artist to be omitted
      

Debugging Tips

  1. Enable Guzzle Debugging:
    $lastfm = LastFmClientFactory::createWithApiKey('key', 'secret', [
        'debug' => fopen('php://output', 'w'),
    ]);
    
  2. Check Response Headers:
    • Last.fm returns X-Lastfm-Error for API errors.
    • Example:
      $response = $lastfm->getClient()->send(new Request('GET', '...'));
      if ($response->hasHeader('X-Lastfm-Error')) {
          $errorCode = $response->getHeader('X-Lastfm-Error')[0];
      }
      

Performance Optimization

  1. Cache Responses:
    use Illuminate\Support\Facades\Cache;
    
    $artist = Cache::remember("lastfm_artist_{$artistName}", now()->addHours(1), function() use ($lastfm, $artistName) {
        return $lastfm->getArtistInfo($artistName);
    });
    
  2. Batch Requests:
    • Last.fm supports multi-get for charts/tags (e.g., getTopArtistsChart() with period=7day).

Extension Points

  1. Custom Middleware:

    $stack = HandlerStack::create();
    $stack->push(Middleware::tap(function ($request) {
        // Modify request (e.g., add headers)
        $request = $request->withHeader('X-Custom-Header', 'value');
        return $request;
    }));
    $lastfm = LastFmClientFactory::createWithApiKey('key', 'secret', ['handler' => $stack]);
    
  2. Override API Endpoint:

    $lastfm = LastFmClientFactory::createWithApiKey('key', 'secret', [
        'base_uri' => 'https://custom-api.lastfm.com',
    ]);
    
  3. Mocking for Tests:

    $mockHandler = HandlerStack::create();
    $mockHandler->push(Middleware::mock(function ($request) {
        return new Response(200, [], json_encode(['artist' => ['name' => 'Mock Artist']]));
    }));
    $lastfm = LastFmClientFactory::createWithApiKey('key', 'secret', ['handler' => $mockHandler]);
    

Configuration Quirks

  1. User-Agent Override:

    • Default: LastFmClient/2.0.0 +https://github.com/calliostro/lastfm-client
    • Override:
      $lastfm = LastFmClientFactory::createWithApiKey('key', 'secret', [
          'headers' => ['User-Agent' => 'MyApp/1.0 (+https://myapp.com)'],
      ]);
      
  2. Timeout Handling:

    • Default: 5.0 seconds.
    • Adjust:
      $lastfm = LastFmClientFactory::createWithApiKey('key', 'secret', ['timeout' => 10.0]);
      

Authentication Flow Tips

  1. Session Expiry:

    • Last.fm sessions expire after 30 minutes of inactivity.
    • Solution: Store session keys and refresh as needed:
      $sessionKey = session('lastfm_session_key');
      if (!$sessionKey) {
          // Redirect to auth flow
      }
      
  2. Mobile Auth Edge Cases:

    • Gotcha: Passwords are sent in plaintext (Last.fm requirement).
    • Mitigation: Use HTTPS and avoid logging credentials.

Laravel-Specific Tips

  1. Store Credentials Securely:

    // .env
    LASTFM_API_KEY=your_key
    LASTFM_API_SECRET=your_secret
    
    // config/services.php
    'lastfm' => [
        'key' => env('LASTFM_API_KEY'),
        'secret' => env('LASTFM_API_SECRET'),
    ],
    
  2. Queue Scrobbling:

    // app/Jobs/ScrobbleTrack.php
    public function handle()
    {
        $lastfm = app(LastFmClient::class);
        $lastfm->scrobbleTrack($this->trackData);
    }
    
  3. Middleware for Auth:

    // app/Http/Middleware/EnsureLastFmSession.php
    public function handle($request, Closure $next)
    {
        if
    
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.
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui
babelqueue/php-sdk
facebook/capi-param-builder-php
babelqueue/symfony
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle