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

Php Sdk Laravel Package

qiniu/php-sdk

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require qiniu/php-sdk
    

    Add the package to your composer.json and run composer update.

  2. Configuration Create a config file (e.g., config/qiniu.php) with your Qiniu credentials:

    return [
        'access_key' => env('QINIU_ACCESS_KEY'),
        'secret_key' => env('QINIU_SECRET_KEY'),
        'bucket' => env('QINIU_BUCKET'),
        'domain' => env('QINIU_DOMAIN', 'https://your-bucket.qiniu.com'),
        'zone' => env('QINIU_ZONE', \Qiniu\Storage\Zone::Zone_Zone0), // Adjust based on region
    ];
    
  3. First Use Case: Upload a File

    use Qiniu\Storage\UploadManager;
    use Qiniu\Auth\Auth;
    
    $auth = new Auth(config('qiniu.access_key'), config('qiniu.secret_key'));
    $uploadManager = new UploadManager();
    
    $token = $auth->uploadToken(config('qiniu.bucket'));
    $ret = $uploadManager->putFile($token, 'file-key', '/path/to/local/file');
    
    if ($ret['key']) {
        return config('qiniu.domain') . '/' . $ret['key'];
    }
    

Implementation Patterns

Common Workflows

  1. File Uploads

    • Direct Uploads: Use UploadManager for local files.
      $ret = $uploadManager->putFile($token, 'unique-key', $localFilePath);
      
    • Resumable Uploads: For large files, use putFile with chunked uploads.
    • Form Uploads: For web forms, use putData with $_FILES data.
      $ret = $uploadManager->putData($token, 'key', file_get_contents($_FILES['file']['tmp_name']));
      
  2. File Management

    • List Files: Use Qiniu\Storage\BucketManager to list objects.
      $bucketManager = new BucketManager($auth, config('qiniu.zone'));
      $items = $bucketManager->listFiles(config('qiniu.bucket'));
      
    • Delete Files:
      $bucketManager->delete(config('qiniu.bucket'), 'file-key');
      
  3. Signed URLs Generate temporary URLs for private files:

    $auth->privateDownloadUrl('file-key', 3600); // URL expires in 1 hour
    
  4. Custom Domains & CORS Configure custom domains via Qiniu console and set CORS rules in the SDK:

    $bucketManager->setBucketCors(config('qiniu.bucket'), [
        'allow_origins' => ['*'],
        'allow_methods' => ['GET', 'HEAD'],
    ]);
    
  5. Integration with Laravel

    • Service Provider: Bind the SDK to the container.
      public function register()
      {
          $this->app->singleton('qiniu.auth', function () {
              return new Auth(config('qiniu.access_key'), config('qiniu.secret_key'));
          });
      }
      
    • Facade: Create a facade for cleaner syntax.
      // QiniuServiceProvider.php
      Facades\Qiniu::shouldRegister(function () {
          return new QiniuService(new Auth(...));
      });
      
    • File Upload Middleware: Validate and process uploads before saving to Qiniu.
      public function handle(Request $request, Closure $next)
      {
          if ($request->hasFile('avatar')) {
              $path = $request->file('avatar')->store('temp');
              // Upload to Qiniu and delete temp file
          }
          return $next($request);
      }
      
  6. Batch Operations Use putMultiFile for multiple uploads:

    $ret = $uploadManager->putMultiFile($token, [
        'key1' => '/path/to/file1',
        'key2' => '/path/to/file2',
    ]);
    
  7. Error Handling Wrap SDK calls in try-catch blocks:

    try {
        $ret = $uploadManager->putFile($token, 'key', $file);
    } catch (\Exception $e) {
        Log::error('Qiniu upload failed: ' . $e->getMessage());
        throw new \RuntimeException('Upload failed', 500);
    }
    

Gotchas and Tips

Pitfalls

  1. Token Expiry

    • Upload tokens expire quickly (default: 3600s). Regenerate tokens for long-running processes.
    • For web forms, generate tokens on-the-fly or use short-lived tokens with client-side SDKs.
  2. File Key Conflicts

    • Qiniu rejects duplicate file keys. Use UUIDs or timestamps to avoid collisions:
      $key = 'uploads/' . Str::uuid() . '.' . $file->getClientOriginalExtension();
      
  3. Zone Misconfiguration

    • Incorrect Zone (e.g., Zone_Zone0 vs. Zone_Zone2) causes slow uploads or failures. Match your bucket’s region.
  4. Large File Timeouts

    • PHP’s default max_execution_time may timeout for large files. Increase it or use chunked uploads:
      ini_set('max_execution_time', 300); // 5 minutes
      
  5. CORS Issues

    • If direct uploads from browsers fail, ensure CORS rules are set in Qiniu’s bucket settings and the SDK’s putPolicy includes callbackUrl:
      $policy = new PutPolicy(config('qiniu.bucket'));
      $policy->callbackUrl = 'https://your-domain.com/callback';
      $token = $auth->uploadToken($policy);
      
  6. Memory Limits

    • putData loads files into memory. For large files, use putFile or stream the file:
      $file = fopen($localPath, 'r');
      $ret = $uploadManager->putFile($token, 'key', $file);
      fclose($file);
      

Debugging Tips

  1. Enable Logging Set the SDK’s log level to debug:

    \Qiniu\Storage\UploadManager::logLevel(\Monolog\Logger::DEBUG);
    
  2. Check HTTP Status Codes Inspect $ret['info']['statusCode'] for errors (e.g., 614 = duplicate key).

  3. Validate Credentials Test credentials with a simple API call:

    $auth->getBucketInfo(config('qiniu.bucket')); // Throws exception if invalid
    
  4. Use Postman for API Testing Manually test Qiniu’s API endpoints (e.g., http://up.qiniu.com) to isolate issues.

Extension Points

  1. Custom Storage Adapter Extend Laravel’s Filesystem to use Qiniu:

    class QiniuAdapter implements FilesystemAdapter
    {
        public function write($path, $contents, $options = [])
        {
            $uploadManager = new UploadManager();
            $token = $this->auth->uploadToken(config('qiniu.bucket'));
            return $uploadManager->putData($token, $path, $contents);
        }
        // Implement other methods...
    }
    
  2. Event Listeners Trigger events after uploads (e.g., generate thumbnails):

    event(new FileUploaded($fileUrl));
    
  3. Webhook Integration Use Qiniu’s callback mechanism to process uploads asynchronously:

    $policy = new PutPolicy(config('qiniu.bucket'));
    $policy->callbackBody = 'filename=$(fname)&size=$(fsize)';
    $policy->callbackUrl = 'https://your-domain.com/qiniu-callback';
    
  4. Fallback to Local Storage Implement a hybrid storage system:

    try {
        $url = $this->qiniu->upload($file);
    } catch (\Exception $e) {
        $url = $this->localStorage->upload($file);
    }
    
  5. Custom Metadata Attach metadata to files during upload:

    $putPolicy = new PutPolicy(config('qiniu.bucket'));
    $putPolicy->persistentOps = 'avthumb/100x100/1e1';
    $putPolicy->persistentNotifyUrl = 'https://your-domain.com/notify';
    $token = $auth->uploadToken($putPolicy);
    
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