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

Sound Cloud Bundle Laravel Package

broz/sound-cloud-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require broz/sound-cloud-bundle:dev-master
    

    Note: Use dev-master explicitly since the package lacks stable releases.

  2. Enable the Bundle: Add to app/AppKernel.php:

    new Broz\SoundCloudBundle\BrozSoundCloudBundle(),
    
  3. Configure Credentials: Register a SoundCloud app at SoundCloud Developer, then add to config.yml:

    broz_sound_cloud:
        client_id:     "%soundcloud_client_id%"  # Define in parameters.yml
        client_secret: "%soundcloud_client_secret%"
    

    Define the parameters in parameters.yml:

    parameters:
        soundcloud_client_id:     "YOUR_CLIENT_ID"
        soundcloud_client_secret: "YOUR_CLIENT_SECRET"
    
  4. First Use Case: Fetch a track in a controller:

    use Broz\SoundCloudBundle\Service\SoundCloudService;
    
    class TrackController extends Controller
    {
        public function showAction($id)
        {
            $track = $this->get('broz_sound_cloud.service')->get('/tracks/' . $id);
            return $this->render('track/show.html.twig', ['track' => $track]);
        }
    }
    

Implementation Patterns

Core Workflows

  1. Service Integration: Inject SoundCloudService via dependency injection:

    class MyService
    {
        private $soundCloud;
    
        public function __construct(SoundCloudService $soundCloud)
        {
            $this->soundCloud = $soundCloud;
        }
    }
    
  2. Common API Calls:

    • Fetch a Resource:
      $track = $this->soundCloud->get('/tracks/123');
      
    • Upload a Track (requires OAuth):
      $this->soundCloud->post('/me/tracks', [
          'track' => $filePath,
          'title' => 'My Track'
      ]);
      
    • Search:
      $results = $this->soundCloud->get('/tracks', [
          'q' => 'laravel',
          'limit' => 10
      ]);
      
  3. OAuth Flow: Redirect users to SoundCloud for auth:

    $url = $this->soundCloud->getAuthorizationUrl(['scope' => 'non-expiring']);
    return new RedirectResponse($url);
    

    Handle the callback:

    $token = $this->soundCloud->getAccessToken($code);
    $this->soundCloud->setAccessToken($token);
    
  4. Pagination: Loop through paginated results:

    $offset = 0;
    do {
        $tracks = $this->soundCloud->get('/me/followings/tracks', [
            'offset' => $offset,
            'limit'  => 20
        ]);
        // Process tracks...
        $offset += 20;
    } while (!empty($tracks));
    
  5. Event Listeners: Subscribe to SoundCloud webhooks (e.g., track uploads):

    # config.yml
    broz_sound_cloud:
        webhook_secret: "your_webhook_secret"
    

    Handle the event in a Symfony event listener:

    class SoundCloudWebhookListener
    {
        public function onKernelRequest(GetResponseEvent $event)
        {
            if ($event->isMasterRequest() &&
                $event->getRequest()->getPathInfo() === '/soundcloud/webhook') {
                $payload = json_decode($event->getRequest()->getContent(), true);
                // Verify and process payload...
            }
        }
    }
    

Gotchas and Tips

Pitfalls

  1. OAuth Scope Limitations:

    • The non-expiring scope is deprecated. Use read/write scopes and handle token refreshes manually.
    • Workaround: Store tokens in the database and implement a refresh logic:
      if ($this->soundCloud->isTokenExpired()) {
          $refreshToken = $this->getRefreshTokenFromDB();
          $this->soundCloud->refreshAccessToken($refreshToken);
      }
      
  2. Rate Limiting:

    • SoundCloud enforces rate limits. Cache responses aggressively:
      $cache = $this->get('cache.app');
      $key = 'soundcloud_track_' . $id;
      if (!$cache->has($key)) {
          $track = $this->soundCloud->get("/tracks/$id");
          $cache->set($key, $track, 300); // Cache for 5 minutes
      } else {
          $track = $cache->get($key);
      }
      
  3. Deprecated Methods:

    • The bundle wraps ise/php-soundcloud (v1.0.0), which may have outdated methods. Check the underlying library’s docs for breaking changes.
  4. Webhook Verification:

    • Always verify webhook payloads using the webhook_secret:
      $expectedSignature = hash_hmac(
          'sha1',
          $event->getRequest()->getContent(),
          $this->container->getParameter('broz_sound_cloud.webhook_secret')
      );
      if (!hash_equals($expectedSignature, $event->getRequest()->headers->get('X-SoundCloud-Signature'))) {
          throw new \RuntimeException('Invalid webhook signature');
      }
      
  5. Error Handling:

    • SoundCloud API errors are thrown as exceptions. Catch them generically:
      try {
          $this->soundCloud->get('/tracks/nonexistent');
      } catch (\Broz\SoundCloudBundle\Exception\SoundCloudException $e) {
          $this->addFlash('error', 'SoundCloud API error: ' . $e->getMessage());
      }
      

Tips

  1. Environment-Specific Config: Use %kernel.environment% to load different credentials for dev/staging/prod:

    parameters:
        soundcloud_client_id:     "%soundcloud_client_id_%kernel.environment%%"
    

    Define in parameters.yml:

    soundcloud_client_id_dev:     "dev_client_id"
    soundcloud_client_id_prod:    "prod_client_id"
    
  2. Testing: Mock the SoundCloudService in PHPUnit:

    $mock = $this->createMock(SoundCloudService::class);
    $mock->method('get')->willReturn(['id' => 123, 'title' => 'Test Track']);
    $this->container->set('broz_sound_cloud.service', $mock);
    
  3. Extending the Bundle:

    • Override the service definition to add custom logic:
      # app/config/services.yml
      services:
          broz_sound_cloud.service:
              class: AppBundle\Service\CustomSoundCloudService
              arguments: ['@broz_sound_cloud.service']
              decorates: 'broz_sound_cloud.service'
      
    • Implement the decorator:
      class CustomSoundCloudService extends SoundCloudService
      {
          public function get($path, $params = [])
          {
              $response = parent::get($path, $params);
              // Add custom logic (e.g., transform responses)
              return $response;
          }
      }
      
  4. Logging: Enable debug logging for API calls:

    # config.yml
    broz_sound_cloud:
        debug: "%kernel.debug%"
    

    Check logs in var/log/dev.log for raw API responses.

  5. File Uploads: For large files, use chunked uploads or a dedicated service like AWS S3 and link to SoundCloud via track[asset_data].

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.
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
babelqueue/php-sdk
facebook/capi-param-builder-php
babelqueue/symfony
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager