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

Oss Sdk Php Laravel Package

aliyuncs/oss-sdk-php

Alibaba Cloud OSS SDK for PHP (V1): connect to Object Storage Service to upload, download, and manage files. Composer install, works on PHP 5.3+ with cURL. Supports common OSS operations for websites and applications with secure, reliable storage.

View on GitHub
Deep Wiki
Context7
## Getting Started

### Minimal Setup
1. **Installation**:
   ```bash
   composer require aliyuncs/oss-sdk-php

Add to composer.json:

"require": {
    "aliyuncs/oss-sdk-php": "^2.0"
}

Autoload:

require_once __DIR__ . '/vendor/autoload.php';
  1. First Use Case: Initialize the client with credentials:

    $client = new \OSS\OssClient('accessKeyId', 'accessKeySecret', 'endpoint');
    
  2. Quick Operations:

    • Upload a file:
      $client->putObject('bucket-name', 'object-key', fopen('local-file', 'r'));
      
    • List buckets:
      $buckets = $client->listBuckets();
      print_r($buckets->getBucketList());
      
  3. Key Files:

    • vendor/aliyuncs/oss-sdk-php/src/OSS/OssClient.php (Core class)
    • vendor/aliyuncs/oss-sdk-php/samples/ (Example workflows)

Implementation Patterns

Core Workflows

  1. File Operations:

    • Upload:
      $client->putObject('bucket', 'key', fopen('file', 'r'), [
          'Content-Type' => 'image/jpeg',
      ]);
      
    • Download:
      $result = $client->getObject('bucket', 'key');
      file_put_contents('local-file', $result->getContent());
      
    • Streaming:
      $client->putObject('bucket', 'key', fopen('php://input', 'r'));
      
  2. Bucket Management:

    • Create/Delete:
      $client->createBucket('bucket-name', \OSS\OssClient::OSS_ACL_TYPE_PUBLIC_READ);
      $client->deleteBucket('bucket-name');
      
    • List Objects:
      $objects = $client->listObjects('bucket-name');
      foreach ($objects->getContents() as $object) {
          echo $object->getKey() . "\n";
      }
      
  3. Pre-Signed URLs:

    • Generate a temporary URL for private objects:
      $url = $client->signUrl('bucket-name', 'key', 3600); // Expires in 1 hour
      
  4. Multipart Uploads:

    • Initiate and complete:
      $uploadId = $client->createMultipartUpload('bucket', 'key')->getUploadId();
      $client->completeMultipartUpload('bucket', 'key', $uploadId, $parts);
      

Integration Tips

  1. Laravel Service Provider:

    use OSS\OssClient;
    
    class OssServiceProvider extends ServiceProvider {
        public function register() {
            $this->app->singleton('oss', function() {
                return new OssClient(
                    config('oss.accessKeyId'),
                    config('oss.accessKeySecret'),
                    config('oss.endpoint')
                );
            });
        }
    }
    

    Configure in .env:

    OSS_ACCESS_KEY_ID=your_key
    OSS_ACCESS_KEY_SECRET=your_secret
    OSS_ENDPOINT=oss-cn-hangzhou.aliyuncs.com
    
  2. Environment Variables: Use OSS_ACCESS_KEY_ID, OSS_ACCESS_KEY_SECRET, and OSS_ENDPOINT for dynamic config:

    $client = new OssClient(
        getenv('OSS_ACCESS_KEY_ID'),
        getenv('OSS_ACCESS_KEY_SECRET'),
        getenv('OSS_ENDPOINT')
    );
    
  3. Error Handling: Wrap operations in try-catch:

    try {
        $client->putObject('bucket', 'key', fopen('file', 'r'));
    } catch (\OSS\Core\OssException $e) {
        \Log::error($e->getMessage());
        abort(500, 'Upload failed');
    }
    
  4. Advanced Features:

    • CORS Configuration:
      $client->putBucketCors('bucket-name', [
          'CORSRules' => [
              [
                  'AllowedHeaders' => ['*'],
                  'AllowedMethods' => ['GET', 'POST'],
                  'AllowedOrigins' => ['*'],
                  'ExposeHeaders' => ['ETag'],
                  'MaxAgeSeconds' => 3600,
              ],
          ],
      ]);
      
    • Lifecycle Rules:
      $client->putBucketLifecycle('bucket-name', [
          'Rules' => [
              [
                  'ID' => 'rule1',
                  'Status' => 'Enabled',
                  'Filter' => ['Prefix' => 'logs/'],
                  'Expiration' => ['Days' => 30],
              ],
          ],
      ]);
      

Gotchas and Tips

Pitfalls

  1. Credentials Handling:

    • Never hardcode credentials. Use environment variables or Laravel's .env.
    • Rotate keys regularly via Alibaba Cloud console.
  2. Endpoint Validation:

    • Ensure the endpoint matches your bucket's region (e.g., oss-cn-hangzhou.aliyuncs.com).
    • Use forcePathStyle: true if encountering DNS issues:
      $client = new OssClient($accessKeyId, $accessKeySecret, $endpoint, [], [
          'forcePathStyle' => true,
      ]);
      
  3. Object Naming:

    • Avoid leading zeros (e.g., 0file.txt) or reserved characters (/, \, ?).
    • Use strictObjectName: true to enforce validation:
      $client = new OssClient(..., ..., ..., [], [
          'strictObjectName' => true,
      ]);
      
  4. Multipart Uploads:

    • Ensure all parts are uploaded within 7 days; otherwise, the upload ID expires.
    • Validate part sizes (max 5GB per part).
  5. CORS Issues:

    • If pre-signed URLs fail, verify CORS rules on the bucket:
      $cors = $client->getBucketCors('bucket-name');
      print_r($cors->getCORSRules());
      
  6. PHP Version Quirks:

    • PHP 5.x: Use ~2.4 to avoid PHP 8+ features.
    • PHP 8+: Ensure oss-sdk-php is updated to ^2.4.2 for compatibility.

Debugging Tips

  1. Enable Debugging:

    $client = new OssClient(..., ..., ..., [
        'debug' => true,
        'logLevel' => \OSS\Core\Logger::LOG_DEBUG,
    ]);
    

    Logs appear in stderr or Laravel's log channel.

  2. Common Errors:

    • InvalidAccessKeyId: Verify accessKeyId/accessKeySecret.
    • BucketAlreadyExists: Check bucket naming conventions (3–63 chars, lowercase, no underscores).
    • NoSuchBucket: Confirm the bucket exists and is in the correct region.
  3. Network Issues:

    • Use proxy: ['host' => 'proxy.example.com', 'port' => 8080] for corporate networks.
    • Increase timeouts if behind slow connections:
      $client = new OssClient(..., ..., ..., [
          'connectTimeout' => 30,
          'readTimeout' => 60,
      ]);
      

Extension Points

  1. Custom Credentials Provider: Implement \OSS\Core\Credentials\CredentialsProviderInterface for dynamic credentials:

    class MyCredentialsProvider implements CredentialsProviderInterface {
        public function getCredentials() {
            return [
                'AccessKeyId' => 'dynamic-key',
                'AccessKeySecret' => 'dynamic-secret',
                'SecurityToken' => null,
            ];
        }
    }
    

    Usage:

    $client = new OssClient(null, null, $endpoint, new MyCredentialsProvider());
    
  2. Middleware for Requests: Extend \OSS\Core\Request to add headers or modify requests:

    $client->addRequestMiddleware(function($request) {
        $request->addHeader('X-My-Custom-Header', 'value');
        return $request;
    });
    
  3. Event Listeners: Subscribe to SDK events (e.g., beforeRequest, afterResponse):

    $client->addEventListener('beforeRequest', function($event) {
        if ($event->getRequest()->getMethod() === 'PUT') {
            $event->getRequest()->addHeader('X-Accel-Buffering', 'no');
        }
    });
    
  4. Batch Operations: Use listObjectsV2 for pagination:

    $objects = $client->listObjectsV2('bucket-name', [
        'maxKeys' => 1000,
        'prefix'
    
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.
besmartand-pro/php-quality-config
sentix/ai-chatbot
codifyo/ts-generator-bundle
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky