Weave 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

Hwcdnbundle Laravel Package

xlabs/hwcdnbundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require xlabs/hwcdnbundle
    

    Add to config/app.php under providers:

    Xlabs\HwcdnBundle\HwcdnBundle::class,
    
  2. Configuration Publish the default config:

    php artisan vendor:publish --provider="Xlabs\HwcdnBundle\HwcdnBundle" --tag=config
    

    Update config/hwcdn.php with your HighWinds CDN credentials (API key, account ID, etc.).

  3. First Use Case: Upload a File

    use Xlabs\HwcdnBundle\Services\HwcdnService;
    
    $hwcdn = app(HwcdnService::class);
    $filePath = storage_path('app/example.jpg');
    $result = $hwcdn->upload($filePath, 'my-bucket-name', 'example.jpg');
    
  4. Verify API Access Test connectivity with:

    $hwcdn->ping(); // Returns true if API is reachable
    

Implementation Patterns

Common Workflows

1. File Management

  • Upload Files

    $result = $hwcdn->upload($localPath, $bucket, $remoteName, [
        'contentType' => 'image/jpeg',
        'cacheControl' => 'public, max-age=31536000',
    ]);
    
    • Supports metadata (e.g., cacheControl, contentType).
    • Returns HwcdnResponse with URL, status, and metadata.
  • Delete Files

    $hwcdn->delete('my-bucket-name', 'example.jpg');
    
  • List Files

    $files = $hwcdn->listFiles('my-bucket-name', [
        'prefix' => 'folder/',
        'limit' => 100,
    ]);
    

2. Bucket Operations

  • Create/Update Bucket

    $hwcdn->createBucket('my-new-bucket', [
        'region' => 'us-east-1',
        'acl' => 'public-read',
    ]);
    
  • Set Bucket Policy

    $hwcdn->setBucketPolicy('my-bucket', file_get_contents('policy.json'));
    

3. URL Generation

  • Generate Signed URLs

    $url = $hwcdn->generateSignedUrl('my-bucket', 'example.jpg', '+1hour');
    
  • CDN URLs

    $cdnUrl = $hwcdn->getCdnUrl('my-bucket', 'example.jpg');
    

4. Event-Driven Workflows

  • Webhook Integration Configure webhooks in config/hwcdn.php:
    'webhooks' => [
        'url' => 'https://your-app.com/hwcdn-webhook',
        'events' => ['file.uploaded', 'file.deleted'],
    ],
    
    Handle events in a controller:
    public function handleWebhook(Request $request) {
        $event = $request->input('event');
        $data = $request->input('data');
        // Process event (e.g., update DB, trigger notifications)
    }
    

5. Batch Operations

  • Upload Multiple Files

    $files = ['file1.jpg', 'file2.jpg'];
    $results = $hwcdn->uploadBatch('my-bucket', $files);
    
  • Parallel Uploads Use Laravel queues for async uploads:

    UploadFileJob::dispatch($filePath, 'my-bucket', 'remote-name.jpg')->onQueue('hwcdn');
    

Integration Tips

Laravel Filesystem Adapter

Extend Laravel’s filesystem to use HWCDN:

// config/filesystems.php
'disks' => [
    'hwcdn' => [
        'driver' => 'hwcdn',
        'bucket' => env('HWCDN_BUCKET'),
        'api_key' => env('HWCDN_API_KEY'),
    ],
],

Usage:

Storage::disk('hwcdn')->put('file.jpg', file_get_contents('local.jpg'));

Blade Directives

Create a Blade directive for CDN URLs:

// app/Providers/BladeServiceProvider.php
Blade::directive('cdn', function ($expression) {
    return "<?php echo app('Xlabs\\HwcdnBundle\\Services\\HwcdnService')->getCdnUrl(...{$expression}); ?>";
});

Usage in Blade:

<img src="{{ cdn('my-bucket', 'image.jpg') }}">

Artisan Commands

Create custom commands for bulk operations:

// app/Console/Commands/SyncLocalToHwcdn.php
public function handle() {
    $files = Storage::disk('local')->files('path/to/files');
    foreach ($files as $file) {
        $hwcdn = app(HwcdnService::class);
        $hwcdn->upload(storage_path($file), 'my-bucket', $file);
    }
}

Gotchas and Tips

Pitfalls

  1. API Rate Limits

    • HighWinds enforces rate limits (e.g., 1000 requests/minute).
    • Solution: Implement exponential backoff in custom logic or use Laravel’s retry helper.
    • Example:
      try {
          $hwcdn->upload(...);
      } catch (\Xlabs\HwcdnBundle\Exceptions\RateLimitExceeded $e) {
          retry()->times(3)->later(2)->try(fn() => $hwcdn->upload(...));
      }
      
  2. File Size Limits

    • Default upload limit: 5GB (configurable via API).
    • Solution: For larger files, use chunked uploads or multipart uploads (not natively supported; implement via custom logic).
  3. CORS Issues

    • If serving files directly from CDN, ensure CORS headers are configured in the bucket policy.
    • Solution: Update bucket policy to include:
      [
          {
              "AllowedHeaders": ["*"],
              "AllowedMethods": ["GET", "HEAD"],
              "AllowedOrigins": ["https://yourdomain.com"],
              "ExposeHeaders": []
          }
      ]
      
  4. Webhook Verification

    • HighWinds webhooks require signature verification.
    • Solution: Validate signatures in your webhook endpoint:
      public function handleWebhook(Request $request) {
          $signature = $request->header('X-HW-Signature');
          $expected = hash_hmac('sha256', $request->getContent(), env('HWCDN_WEBHOOK_SECRET'));
          if (!hash_equals($expected, $signature)) {
              abort(403);
          }
          // Process event
      }
      
  5. Retry Logic for Failures

    • Network issues or transient errors may occur.
    • Solution: Wrap API calls in retry logic:
      $hwcdn->withRetry(3, 100)->upload(...);
      

Debugging

  1. Enable Debug Mode Set in config/hwcdn.php:

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

    Logs API requests/responses to storage/logs/hwcdn.log.

  2. Common Errors

    Error Cause Solution
    InvalidCredentials Wrong API key/account ID Check config/hwcdn.php
    BucketNotFound Bucket doesn’t exist Create bucket first
    FileNotFound File missing in bucket Verify remote path
    SignatureDoesNotMatch Webhook signature mismatch Regenerate secret in config
  3. Logging API Responses Extend the service to log responses:

    $hwcdn = app(HwcdnService::class);
    $hwcdn->setLogger(app(\Psr\Log\LoggerInterface::class));
    

Extension Points

  1. Custom Storage Adapter Extend HwcdnAdapter to add features:

    namespace App\Services;
    
    use Xlabs\HwcdnBundle\Adapters\HwcdnAdapter;
    
    class CustomHwcdnAdapter extends HwcdnAdapter {
        public function customMethod($param) {
            // Add custom logic
            return $this->client->customCall($param);
        }
    }
    
  2. Event Listeners Listen to HWCDN events (e.g., HwcdnFileUploaded):

    // app/Providers/EventServiceProvider.php
    protected $listen = [
        \Xlabs\HwcdnBundle\Events\HwcdnFileUploaded::class => [
            \App\Listeners\LogUploadedFile::class,
        ],
    ];
    
  3. **Middleware

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.
xiloryx/log-collector
a21ns1g4ts/filament-stripe
la-php/laravel-admin
artisan-build/community-prompts
vleroy/smart
ayles-software/laravel-australian-public-holidays
cboxdk/laravel-id-spatie
cboxdk/laravel-id-billing
cboxdk/laravel-id-billing-bridge
simple-as-fuck/php-performance-log
hsluv/hsluv
seampact/codegen
seampact/hooks
seampact/ir
mehedimi/laravel-amp-mail
happones/laravel-vue-i18n-generator
jwerd/inertia-table
siberfx/flysystem-wasabi
hollyit/token-replace
ippanelcom/laravel-sdk