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

binarythinking/lastfm-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require binarythinking/lastfm-bundle:dev-master
    

    Register the bundle in config/bundles.php (Symfony 4+):

    return [
        // ...
        BinaryThinking\LastfmBundle\BinaryThinkingLastfmBundle::class => ['all' => true],
    ];
    
  2. 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)%"
    
  3. 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]);
    }
    

Implementation Patterns

Core Workflows

  1. Service Integration: Inject LastfmService into controllers/services to interact with the API:

    public function __construct(private LastfmService $lastfm) {}
    
  2. Common Use Cases:

    • Artist Data:
      $artistInfo = $this->lastfm->getArtistInfo('Radiohead');
      $similarArtists = $this->lastfm->getArtistSimilar($artistName);
      
    • User Library:
      $recentTracks = $this->lastfm->getUserRecentTracks('username');
      $lovedTracks = $this->lastfm->getUserLovedTracks('username');
      
    • Charts:
      $topArtists = $this->lastfm->getTopArtists();
      $topTracks = $this->lastfm->getTopTracks();
      
  3. Pagination: Handle paginated responses (e.g., getArtistTopTracks):

    $tracks = $this->lastfm->getArtistTopTracks($artistName, 1, 5); // Page 1, 5 items
    
  4. Geo Data: Fetch location-based charts:

    $geoTopArtists = $this->lastfm->getTopArtistsByCountry('US');
    
  5. Tagging: Explore tags for artists/albums:

    $tags = $this->lastfm->getArtistTags('The Beatles');
    

Advanced Patterns

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

Gotchas and Tips

Pitfalls

  1. API Key Limits:

    • Last.fm enforces rate limits. Cache responses aggressively to avoid hitting limits.
    • Example: Avoid calling getUserRecentTracks in a loop without delays.
  2. Deprecated Methods:

    • Some methods (e.g., getArtistBio) may return null or throw exceptions if the API endpoint is deprecated. Check the Last.fm API docs for updates.
  3. Error Handling:

    • The bundle may not throw exceptions for all API errors. Wrap calls in try-catch:
      try {
          $data = $this->lastfm->getArtistInfo('InvalidArtist');
      } catch (\Exception $e) {
          // Handle gracefully (e.g., return 404)
      }
      
  4. Configuration Overrides:

    • If using Symfony Flex, ensure 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
      

Debugging Tips

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

  2. Validate API Key: Test your key with a simple endpoint first:

    $this->lastfm->getArtistInfo('Radiohead'); // Should return data if key is valid
    
  3. Handle Missing Data: Some API responses may return empty arrays or null. Normalize data before use:

    $tracks = $this->lastfm->getArtistTopTracks($artistName)['tracks'] ?? [];
    

Extension Points

  1. 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']
    
  2. 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
    
  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']
    
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.
sentix/ai-chatbot
terminal42/code-quality-tools
codifyo/ts-generator-bundle
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky