Installation:
composer require dwd/qiniu-sdk-bundle:dev-master
Add the repository to composer.json under repositories (as shown in README).
Run composer update.
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
Register Bundle:
Add to app/AppKernel.php:
new DWD\QiniuSdkBundle\DWDQiniuSdkBundle(),
Clear Cache:
php app/console cache:clear
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);
}
File Uploads:
put() for dynamic content (e.g., API responses, logs).
$qiniu->put('log_2023.txt', 'Error: File not found');
putFile() for static assets (images, PDFs).
$qiniu->putFile('user_avatar.jpg', '/uploads/avatar.jpg');
$qiniu->put('large_file.zip', fopen('php://input', 'r'));
File Management:
$qiniu->delete('old_key.txt'); // Single
$qiniu->batchDelete(['key1', 'key2']); // Batch
mv() for internal bucket operations.
$qiniu->mv('old_key', 'new_key'); // Same bucket
$qiniu->mv('old_key', 'new_key', 'new_bucket'); // Cross-bucket
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.
Dependency Injection: Inject the service directly into controllers/services:
public function __construct(DWD\QiniuSdkBundle\QiniuService $qiniu) {
$this->qiniu = $qiniu;
}
Event Listeners: Trigger actions post-upload (e.g., thumbnail generation):
$this->get('event_dispatcher')->dispatch('qiniu.upload.success', new QiniuEvent($result));
Validation: Validate keys/buckets before operations:
if (empty($this->getParameter('qiniu_sdk_bucket'))) {
throw new \RuntimeException('Qiniu bucket not configured.');
}
Error Handling: Wrap Qiniu operations in try-catch:
try {
$result = $qiniu->putFile('key', $file);
} catch (\Exception $e) {
$this->addFlash('error', 'Upload failed: ' . $e->getMessage());
}
Configuration Overrides:
parameters.yml take precedence over config.yml. Ensure no duplicates exist.parameters.yml.dist for defaults and override in parameters.yml.Key Collisions:
$key = 'user_' . $userId . '_' . time() . '.jpg';
File Size Limits:
Cross-Bucket Operations:
mv() with a new bucket requires bucket permissions (not just key access).Domain Configuration:
qiniu_sdk_domain is missing, public URLs will be http://<bucket>.qiniu.com/key.Enable Qiniu Logging:
Add to app/config/config.yml:
dwd_qiniu_sdk:
debug: true # If supported; otherwise, use the official SDK's logger.
\Qiniu\Storage\Config::putLogFile('qiniu.log');
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).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: [...]
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).
});
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);
Fallback to Official SDK: For advanced features, inject the official SDK:
use Qiniu\Storage\BucketManager;
public function __construct(BucketManager $bucketManager) {
$this->bucketManager = $bucketManager;
}
How can I help you explore Laravel packages today?