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

Last Fm Client Bundle Laravel Package

calliostro/last-fm-client-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

  1. Installation:

    composer require calliostro/last-fm-client-bundle
    

    Ensure calliostro/lastfm-client (v2.0.0+) is also installed as a dependency.

  2. Configuration: Publish the default config:

    php bin/console config:dump-reference calliostro_lastfm
    

    Update config/packages/calliostro_lastfm.yaml with your API key and rate-limiting settings:

    calliostro_lastfm:
        api_key: '%env(LASTFM_API_KEY)%'
        rate_limiter: true
        limit: 1000  # requests/hour
    
  3. First Use Case: Inject Calliostro\LastFm\LastFmClient into a service/controller:

    use Calliostro\LastFm\LastFmClient;
    
    class ArtistController
    {
        public function __construct(private LastFmClient $lastFmClient) {}
    
        public function show(string $artistName)
        {
            $info = $this->lastFmClient->getArtistInfo($artistName);
            return response()->json($info);
        }
    }
    

Implementation Patterns

Autowiring & Dependency Injection

  • Type-hinted injection is fully supported. Prefer constructor injection for services:
    public function __construct(
        private LastFmClient $lastFmClient,
        private RateLimiterInterface $rateLimiter
    ) {}
    
  • Service Locator: Avoid container->get(); use constructor injection or #[Inject] attribute (Symfony 6.4+).

Rate Limiting

  • Enable via config (rate_limiter: true). The bundle integrates with symfony/rate-limiter:
    calliostro_lastfm:
        rate_limiter:
            enabled: true
            limit: 1000
            interval: 3600  # seconds
    
  • Customize rate limits per endpoint by extending LastFmClient or using middleware.

Common Workflows

  1. Fetching Data:
    $tracks = $lastFmClient->getRecentTracks('username');
    $albums = $lastFmClient->getTopAlbums('artist', limit: 5);
    
  2. Error Handling: Use try/catch with Calliostro\LastFm\Exception\LastFmException:
    try {
        $lastFmClient->getArtistInfo('nonexistent_artist');
    } catch (LastFmException $e) {
        // Handle API errors (e.g., rate limits, invalid requests)
    }
    
  3. Testing: Mock LastFmClient in tests:
    $this->mock(LastFmClient::class)->shouldReceive('getArtistInfo')->andReturn($mockData);
    

Integration with Symfony Components

  • Messenger: Dispatch API calls as async messages:
    $this->messageBus->dispatch(new FetchArtistInfo($artistName));
    
  • Cache: Cache responses with Symfony Cache component:
    $cache = $this->cacheItemPool->getItem('lastfm_artist_' . $artistName);
    if (!$cache->isHit()) {
        $cache->set($lastFmClient->getArtistInfo($artistName));
        $cache->expiresAfter(3600);
    }
    

Gotchas and Tips

Breaking Changes (v2.0.0)

  1. Namespace Update:

    • Old: Calliostro\LastFm\LastFmService
    • New: Calliostro\LastFm\LastFmClient (capital F).
    • Update all service references and imports.
  2. Configuration:

    • Old: lastfm key in config.
    • New: calliostro_lastfm key.
    • Run php bin/console config:dump-reference calliostro_lastfm to regenerate config.
  3. Dependency:

    • Replace calliostro/php-lastfm-api with calliostro/lastfm-client (v2.0.0+).
  4. Migration:

    • Follow the UPGRADE.md guide for step-by-step instructions.

Debugging

  • Rate Limiting:

    • Check Symfony’s RateLimiter logs for throttling issues:
      bin/console debug:container symfony_rate_limiter
      
    • Customize limits per endpoint by overriding the LastFmClient or using middleware.
  • API Errors:

    • Enable debug mode in config:
      calliostro_lastfm:
          debug: true
      
    • Logs will include raw API responses for troubleshooting.

Performance Tips

  • Batch Requests: Use the batch() method to reduce HTTP calls:
    $results = $lastFmClient->batch([
        'getArtistInfo' => ['artist' => 'Arctic Monkeys'],
        'getTopTracks' => ['artist' => 'Arctic Monkeys', 'period' => '7day'],
    ]);
    
  • Caching: Cache responses aggressively (Last.fm API has generous TTLs for most endpoints):
    $cacheKey = 'lastfm_top_artists_' . $period;
    if (!$cached = cache()->get($cacheKey)) {
        $cached = $lastFmClient->getTopArtists($period);
        cache()->put($cacheKey, $cached, now()->addHours(1));
    }
    

Extension Points

  1. Custom Clients: Extend LastFmClient to add domain-specific methods:

    class CustomLastFmClient extends LastFmClient
    {
        public function getArtistTopFans(string $artistName, int $limit = 10): array
        {
            return $this->call('artist.getTopFans', [
                'artist' => $artistName,
                'limit' => $limit,
            ]);
        }
    }
    

    Register as a service:

    services:
        App\Service\CustomLastFmClient:
            arguments:
                $client: '@calliostro_lastfm.client'
    
  2. Middleware: Add request/response middleware:

    $lastFmClient->getMiddlewareStack()->add(
        new AddUserAgentMiddleware('MyApp/1.0')
    );
    
  3. Event Listeners: Subscribe to LastFmClientEvents (e.g., BeforeRequest, AfterResponse) for logging/auditing:

    $dispatcher->addListener(LastFmClientEvents::BEFORE_REQUEST, function (BeforeRequestEvent $event) {
        // Log request details
    });
    
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.
emuniq/filament-browser-notifications
syriable/filament-translator
hungnm28/livewire-form
wenprise/eloquent
crudly/encrypted
fadion/bouncy
cuci/prototurk-sdk
gos/pubsub-router-bundle
cuci/prototurk-sdk-symfony
clementtalleu/easyadmin-markdown-bundle
codeflextech/permission-manager
karnoweb/livewire-datepicker
sayedenam/sayed-dashboard
milito/query-filter
apiboxsym/user-bundle
apiboxsym/health-check-bundle
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui