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

Cdn Bundle Laravel Package

bastsys/cdn-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require bastsys/cdn-bundle
    

    Add to config/app.php under providers:

    Bastsys\CdnBundle\CdnServiceProvider::class,
    

    Publish config (if needed):

    php artisan vendor:publish --provider="Bastsys\CdnBundle\CdnServiceProvider"
    
  2. Configuration: Edit config/cdn.php to define CDN endpoints (e.g., AWS CloudFront, Akamai, or custom):

    'endpoints' => [
        'default' => [
            'url' => 'https://cdn.example.com',
            'bucket' => 'your-bucket-name',
        ],
    ],
    
  3. First Use Case: Upload a file via the facade:

    use Bastsys\CdnBundle\Facades\Cdn;
    
    $path = Cdn::upload('path/to/local/file.jpg', 'remote/path/file.jpg');
    

    Outputs the CDN URL (e.g., https://cdn.example.com/remote/path/file.jpg).


Implementation Patterns

Core Workflows

  1. File Uploads:

    • Use Cdn::upload() for direct uploads with optional metadata:
      $path = Cdn::upload('local.jpg', 'remote.jpg', [
          'contentType' => 'image/jpeg',
          'cacheControl' => 'public, max-age=31536000',
      ]);
      
    • Chain with Cdn::getUrl() to fetch the CDN path:
      $cdnUrl = Cdn::getUrl('remote.jpg');
      
  2. Asset Management:

    • Versioning: Append a hash to filenames for cache busting:
      $versionedPath = Cdn::version('remote.jpg', 'v1');
      
    • Deletion: Remove files via:
      Cdn::delete('remote.jpg');
      
  3. Integration with Laravel:

    • Storage Disk: Use the cdn disk in filesystem.php:
      'disks' => [
          'cdn' => [
              'driver' => 'cdn',
              'endpoint' => 'default',
          ],
      ],
      
    • Blade Directives: Create a custom directive for CDN URLs:
      Blade::directive('cdn', function ($path) {
          return "<?php echo Bastsys\CdnBundle\Facades\Cdn::getUrl($path); ?>";
      });
      
      Usage:
      <img src="{{ cdn('remote.jpg') }}">
      
  4. Batch Operations:

    • Upload multiple files:
      $results = Cdn::uploadMultiple([
          'local1.jpg' => 'remote1.jpg',
          'local2.jpg' => 'remote2.jpg',
      ]);
      

Gotchas and Tips

Pitfalls

  1. Endpoint Configuration:

    • Missing Endpoints: Ensure config/cdn.php has at least one defined endpoint. Throws InvalidArgumentException if not.
    • Bucket Permissions: Verify the CDN bucket has proper IAM/S3 permissions for uploads/deletes. Test with a single file first.
  2. File Path Handling:

    • Trailing Slashes: Avoid trailing slashes in remote paths (e.g., remote/path/ vs. remote/path). The package trims them but may cause silent failures.
    • Reserved Characters: Sanitize filenames to avoid CDN-specific issues (e.g., spaces, special chars). Use Str::slug() if needed.
  3. Cache Invalidation:

    • Manual Cache Control: The package doesn’t auto-invalidate CDN caches. Use CDN-specific tools (e.g., CloudFront invalidation) or set cacheControl in metadata.
  4. Local Fallback:

    • No Local Storage: The package assumes files exist locally. For dynamic content, combine with Laravel’s Storage facade:
      $localPath = Storage::disk('local')->put('file.jpg', $content);
      Cdn::upload($localPath, 'remote.jpg');
      

Debugging

  1. Logs: Enable debug mode in config/cdn.php:

    'debug' => env('CDN_DEBUG', false),
    

    Logs upload/deletion attempts to storage/logs/cdn.log.

  2. Testing:

    • Mock the CdnManager in tests:
      $this->app->instance(\Bastsys\CdnBundle\Contracts\CdnManager::class, Mockery::mock());
      
    • Use Artisan::call() to test commands:
      $this->artisan('cdn:purge')->assertExitCode(0);
      

Extension Points

  1. Custom Drivers:

    • Extend Bastsys\CdnBundle\Contracts\CdnDriver for unsupported CDNs (e.g., Backblaze B2):
      class BackblazeDriver implements CdnDriver {
          public function upload($localPath, $remotePath, array $options) {
              // Custom logic
          }
      }
      
    • Register in CdnServiceProvider:
      $this->app->bind(CdnDriver::class, function () {
          return new BackblazeDriver();
      });
      
  2. Events:

    • Listen for upload/delete events via CdnEvents:
      event(new CdnUploading($localPath, $remotePath));
      
    • Publish events in EventServiceProvider:
      protected $listen = [
          CdnUploading::class => [
              YourListener::class,
          ],
      ];
      
  3. Middleware:

    • Add CDN-specific middleware to routes:
      Route::middleware(['cdn.verify'])->group(function () {
          // Routes requiring CDN access
      });
      
    • Implement CdnMiddleware contract to validate CDN tokens/headers.

Performance Tips

  1. Parallel Uploads:

    • Use Laravel’s parallel helper for batch uploads:
      parallel([
          fn() => Cdn::upload('file1.jpg', 'remote1.jpg'),
          fn() => Cdn::upload('file2.jpg', 'remote2.jpg'),
      ]);
      
  2. Lazy Loading:

    • Defer CDN URL generation until runtime to reduce Blade template processing:
      // In a service class
      public function getCdnUrl($path) {
          return Cdn::getUrl($path);
      }
      
      <img src="{{ $service->getCdnUrl('remote.jpg') }}">
      
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.
terminal42/code-quality-tools
codifyo/ts-generator-bundle
andydefer/laravel-cluster
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