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

clarity-project/cdn-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require clarity-project/cdn-bundle
    

    Add to config/bundles.php:

    return [
        // ...
        ClarityProject\CdnBundle\ClarityCdnBundle::class => ['all' => true],
    ];
    
  2. Configuration: Update config/packages/clarity_cdn.yaml (create if missing):

    clarity_cdn:
        default_cdn: 'local'  # or 'remote'
        cdn:
            local:
                type: 'local'
                path: '%kernel.project_dir%/public/uploads'
            remote:
                type: 's3'  # or 'ftp', 'rackspace', etc.
                options: { /* provider-specific config */ }
    
  3. First Use Case:

    • Upload a file:
      use ClarityProject\CdnBundle\Manager\CdnManager;
      
      $cdnManager = $this->container->get('clarity_cdn.manager');
      $filePath = $cdnManager->upload('local', $file, 'user_avatars');
      
    • Generate a URL:
      $url = $cdnManager->getUrl('local', $filePath);
      

Key Files to Review

  • config/packages/clarity_cdn.yaml: Default configuration.
  • src/Manager/CdnManager.php: Core logic for uploads/URLs.
  • Resources/doc/index.md: Official documentation (if available).

Implementation Patterns

Workflows

1. File Upload & Storage

  • Abstract Paths: Store only abstract paths (e.g., user_avatars/123.jpg) in the database, not full URLs.
    $abstractPath = $cdnManager->upload('remote', $file, 'user_avatars');
    // Save `$abstractPath` to DB, not the full URL.
    
  • Dynamic CDN Switching: Change CDN providers without altering application logic.
    // Switch to 'remote' CDN in config, no code changes needed.
    

2. URL Generation

  • Consistent URLs: Generate URLs dynamically based on abstract paths.
    $url = $cdnManager->getUrl($cdnName, $abstractPath);
    // Use `$url` in templates/views.
    
  • Twig Integration:
    <img src="{{ clarity_cdn_url('local', entity.imagePath) }}">
    
    Add to twig.config.yaml:
    twig:
        globals:
            clarity_cdn_url: '@clarity_cdn.twig.url_generator'
    

3. File Deletion

  • Safe Deletion: Remove files from CDN without local copies.
    $cdnManager->delete('local', $abstractPath);
    

4. Batch Operations

  • Bulk Uploads:
    foreach ($files as $file) {
        $cdnManager->upload('remote', $file, 'batch_uploads');
    }
    

Integration Tips

Laravel-Specific Adaptations

  1. Service Provider Binding: Bind the CDN manager in AppServiceProvider:

    public function register()
    {
        $this->app->bind('clarity_cdn.manager', function ($app) {
            return new \ClarityProject\CdnBundle\Manager\CdnManager(
                $app['clarity_cdn.config'],
                $app['filesystem']
            );
        });
    }
    
  2. Filesystem Integration: Use Laravel’s filesystem to handle local uploads:

    # config/filesystems.php
    'disks' => [
        'cdn_local' => [
            'driver' => 'local',
            'root' => storage_path('app/cdn'),
        ],
    ],
    

    Update clarity_cdn.yaml:

    clarity_cdn:
        cdn:
            local:
                type: 'local'
                filesystem: 'cdn_local'  # Use Laravel's filesystem
    
  3. Artisan Commands: Extend the bundle with custom commands for maintenance:

    namespace App\Console\Commands;
    
    use ClarityProject\CdnBundle\Manager\CdnManager;
    use Illuminate\Console\Command;
    
    class SyncCdnFiles extends Command
    {
        protected $cdnManager;
    
        public function __construct(CdnManager $cdnManager)
        {
            parent::__construct();
            $this->cdnManager = $cdnManager;
        }
    
        public function handle()
        {
            // Sync logic here
        }
    }
    
  4. Event Listeners: Trigger actions on upload/deletion (e.g., thumbnail generation):

    // config/packages/clarity_cdn.yaml
    clarity_cdn:
        events:
            upload: ['App\Events\HandleUploadedFile']
            delete: ['App\Events\HandleDeletedFile']
    

Gotchas and Tips

Pitfalls

  1. Abstract Path Collisions:

    • Issue: Using the same abstract path (e.g., profile.jpg) for multiple files.
    • Fix: Append unique identifiers (e.g., profile_123.jpg or UUIDs).
      $abstractPath = 'user_avatars/' . uniqid() . '_' . $file->getClientOriginalName();
      
  2. CDN Provider Quirks:

    • S3: Ensure IAM roles have proper permissions for PutObject, GetObject, and DeleteObject.
    • FTP: Timeout issues may require retries or connection pooling.
    • Local: Verify path in config is writable (chmod -R 775 public/uploads).
  3. Caching Headaches:

    • Issue: URLs not updating after file changes (e.g., due to CDN caching).
    • Fix: Append a version query string or cache-busting token:
      $url = $cdnManager->getUrl('remote', $abstractPath) . '?v=' . filemtime($localPath);
      
  4. Symfony vs. Laravel Mismatches:

    • Issue: Bundle assumes Symfony’s ContainerInterface; Laravel uses Illuminate\Container\Container.
    • Fix: Use dependency injection or adapt the service provider (see Implementation Patterns).
  5. Deprecated Methods:

    • The bundle is outdated (last release: 2014). Some methods may not exist in newer Symfony/Laravel versions.
    • Workaround: Extend the bundle or fork it:
      // Override CdnManager in a trait or subclass
      namespace App\Services;
      
      use ClarityProject\CdnBundle\Manager\CdnManager as BaseCdnManager;
      
      class CdnManager extends BaseCdnManager
      {
          public function modernUpload($cdnName, $file, $directory)
          {
              // Custom logic
          }
      }
      

Debugging

  1. Log Uploads/Deletions: Enable debug mode in clarity_cdn.yaml:

    clarity_cdn:
        debug: true
    

    Check logs for errors (e.g., permission denied, connection issues).

  2. Verify Abstract Paths: Dump abstract paths to ensure they’re unique and correctly formatted:

    dd($cdnManager->upload('local', $file, 'test'));
    
  3. Test Locally First: Use the local CDN for development to avoid remote provider costs:

    clarity_cdn:
        default_cdn: 'local'
    

Extension Points

  1. Custom CDN Drivers: Extend the bundle by adding new driver classes. Example for a custom driver:

    namespace App\Cdn\Driver;
    
    use ClarityProject\CdnBundle\Driver\AbstractDriver;
    
    class CustomDriver extends AbstractDriver
    {
        public function upload($file, $directory)
        {
            // Custom upload logic (e.g., to a CDN API)
        }
    
        public function getUrl($path)
        {
            // Custom URL generation
        }
    }
    

    Register in clarity_cdn.yaml:

    clarity_cdn:
        cdn:
            custom:
                type: 'custom'
                class: 'App\Cdn\Driver\CustomDriver'
    
  2. Pre/Post Hooks: Add callbacks for uploads/deletions via events (Symfony-style):

    clarity_cdn:
        events:
            upload:
                - ['App\Services\ThumbnailGenerator', 'generate']
                - ['App\Services\Logger', 'logUpload']
    
  3. Middleware for URLs: Proxy CDN URLs through Laravel middleware to add auth or analytics:

    Route::get('/cdn/{cdn}/{path}', function ($cdn, $path) {
        $cdnManager = app('clarity_cdn.manager');
        $url = $cdnManager->getUrl($cdn, $path);
        // Add middleware logic (e.g., rate limiting)
        return redirect()->to($url);
    });
    
  4. Fallback Mechanisms:

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.
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
atriumphp/atrium
sandermuller/package-boost-laravel
sandermuller/boost-skills
redaxo/core
yusufgenc/filament-api-forge
l3aro/rating-star-for-filament