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

Qiniu Sdk Bundle Laravel Package

dwd/qiniu-sdk-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require dwd/qiniu-sdk-bundle:dev-master
    

    Add the repository to composer.json under repositories (as shown in README). Run composer update.

  2. Configuration: Add Qiniu credentials to app/config/parameters.yml:

    parameters:
        qiniu_sdk_accessKey: "YOUR_ACCESS_KEY"
        qiniu_sdk_secretKey: "YOUR_SECRET_KEY"
        qiniu_sdk_bucket: "your-bucket-name"
        qiniu_sdk_domain: "http://your-domain.com"  # Optional, e.g., CDN URL
    
  3. Register Bundle: Add to app/AppKernel.php:

    new DWD\QiniuSdkBundle\DWDQiniuSdkBundle(),
    
  4. Clear Cache:

    php app/console cache:clear
    

First Use Case

Upload a file via a Symfony controller:

use Symfony\Component\HttpFoundation\Request;

public function uploadAction(Request $request) {
    $qiniu = $this->get('dwd_qiniu_sdk');
    $file = $request->files->get('file');
    $result = $qiniu->putFile('unique_key_name', $file->getPathname());
    return new JsonResponse($result);
}

Implementation Patterns

Core Workflows

  1. File Uploads:

    • Direct Content: Use put() for dynamic content (e.g., API responses, logs).
      $qiniu->put('log_2023.txt', 'Error: File not found');
      
    • Local Files: Use putFile() for static assets (images, PDFs).
      $qiniu->putFile('user_avatar.jpg', '/uploads/avatar.jpg');
      
    • Streaming: For large files, stream directly from a resource (e.g., HTTP request):
      $qiniu->put('large_file.zip', fopen('php://input', 'r'));
      
  2. File Management:

    • Deletion: Single or batch deletion.
      $qiniu->delete('old_key.txt'); // Single
      $qiniu->batchDelete(['key1', 'key2']); // Batch
      
    • Renaming/Moving: Use mv() for internal bucket operations.
      $qiniu->mv('old_key', 'new_key'); // Same bucket
      $qiniu->mv('old_key', 'new_key', 'new_bucket'); // Cross-bucket
      
  3. URL Generation: Dynamically generate public URLs (if domain is configured):

    $url = $this->getParameter('qiniu_sdk_domain') . '/key_name';
    // Or extend the bundle to add a `getPublicUrl()` method.
    

Integration Tips

  1. Dependency Injection: Inject the service directly into controllers/services:

    public function __construct(DWD\QiniuSdkBundle\QiniuService $qiniu) {
        $this->qiniu = $qiniu;
    }
    
  2. Event Listeners: Trigger actions post-upload (e.g., thumbnail generation):

    $this->get('event_dispatcher')->dispatch('qiniu.upload.success', new QiniuEvent($result));
    
  3. Validation: Validate keys/buckets before operations:

    if (empty($this->getParameter('qiniu_sdk_bucket'))) {
        throw new \RuntimeException('Qiniu bucket not configured.');
    }
    
  4. Error Handling: Wrap Qiniu operations in try-catch:

    try {
        $result = $qiniu->putFile('key', $file);
    } catch (\Exception $e) {
        $this->addFlash('error', 'Upload failed: ' . $e->getMessage());
    }
    

Gotchas and Tips

Pitfalls

  1. Configuration Overrides:

    • Parameters in parameters.yml take precedence over config.yml. Ensure no duplicates exist.
    • Fix: Use parameters.yml.dist for defaults and override in parameters.yml.
  2. Key Collisions:

    • Qiniu keys must be unique. Reusing keys overwrites files silently.
    • Fix: Append timestamps/UUIDs to keys:
      $key = 'user_' . $userId . '_' . time() . '.jpg';
      
  3. File Size Limits:

    • Qiniu’s default limit is 100MB. Larger files require chunked uploads (not supported by this bundle).
    • Fix: Use the official PHP SDK for large files.
  4. Cross-Bucket Operations:

    • mv() with a new bucket requires bucket permissions (not just key access).
    • Fix: Test permissions via Qiniu’s Bucket Manager.
  5. Domain Configuration:

    • If qiniu_sdk_domain is missing, public URLs will be http://<bucket>.qiniu.com/key.
    • Fix: Configure a custom domain in Qiniu’s Domain Management.

Debugging

  1. Enable Qiniu Logging: Add to app/config/config.yml:

    dwd_qiniu_sdk:
        debug: true  # If supported; otherwise, use the official SDK's logger.
    
    • Alternative: Use the official SDK’s logger:
      \Qiniu\Storage\Config::putLogFile('qiniu.log');
      
  2. Common Errors:

    • Access Denied: Verify accessKey/secretKey and bucket permissions.
    • Key not exist: Check for typos in keys or ensure files were uploaded.
    • Invalid argument: Validate file paths (use absolute paths for putFile).

Extension Points

  1. Custom Storage Classes: Extend the bundle’s QiniuService to add methods (e.g., generatePresignedUrl):

    namespace App\Service;
    use DWD\QiniuSdkBundle\QiniuService as BaseQiniuService;
    
    class QiniuService extends BaseQiniuService {
        public function generatePresignedUrl($key, $expires = 3600) {
            // Implement using Qiniu's presigned URL logic.
        }
    }
    

    Override the service in services.yml:

    services:
        dwd_qiniu_sdk:
            class: App\Service\QiniuService
            arguments: [...]
    
  2. Event-Driven Workflows: Dispatch events for uploads/deletions:

    // In QiniuService.php
    $this->dispatch('qiniu.upload', new QiniuEvent($result));
    

    Listen in a controller/service:

    $dispatcher->addListener('qiniu.upload', function ($event) {
        // Process upload (e.g., update database, send notifications).
    });
    
  3. Multi-Bucket Support: Dynamically switch buckets by extending the service:

    public function setBucket($bucket) {
        $this->bucket = $bucket;
    }
    

    Use in controllers:

    $qiniu->setBucket('backup-bucket')->putFile('key', $file);
    
  4. Fallback to Official SDK: For advanced features, inject the official SDK:

    use Qiniu\Storage\BucketManager;
    
    public function __construct(BucketManager $bucketManager) {
        $this->bucketManager = $bucketManager;
    }
    
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.
emuniq/filament-browser-notifications
syriable/filament-translator
hungnm28/livewire-form
wenprise/eloquent
crudly/encrypted
fadion/bouncy
cuci/prototurk-sdk
gos/pubsub-router-bundle
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