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

    composer require aliyuncs/oss-sdk-php
    

    For V2 (recommended):

    composer require alibabacloud/oss-php-sdk-v2
    
  2. First Use Case: Upload a File

    use OSS\OssClient;
    use OSS\Core\Auth\Credentials\Credentials;
    
    $accessKeyId = 'your-access-key-id';
    $accessKeySecret = 'your-access-key-secret';
    $endpoint = 'https://oss-cn-hangzhou.aliyuncs.com'; // Replace with your endpoint
    $bucket = 'your-bucket-name';
    
    $ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint);
    $result = $ossClient->putObject($bucket, 'example.txt', __DIR__ . '/example.txt');
    
  3. Where to Look First


Implementation Patterns

Core Workflows

  1. Authentication & Initialization

    • Credentials Management: Use environment variables or Laravel's .env for secrets.
      $credentials = new Credentials(env('OSS_ACCESS_KEY_ID'), env('OSS_ACCESS_KEY_SECRET'));
      $ossClient = new OssClient($credentials, env('OSS_ENDPOINT'));
      
    • Service Container Binding (Laravel):
      $app->singleton(OssClient::class, function ($app) {
          return new OssClient(
              $app['config']['oss.access_key_id'],
              $app['config']['oss.access_key_secret'],
              $app['config']['oss.endpoint']
          );
      });
      
  2. File Operations

    • Upload/Download with Progress:
      // Upload with progress callback (V2)
      $ossClient->putObjectV2(
          $bucket,
          'large-file.zip',
          __DIR__ . '/large-file.zip',
          [
              'progress_callback' => function ($progress) {
                  Log::debug("Upload progress: {$progress['percent']}%");
              }
          ]
      );
      
    • Streaming Uploads:
      $ossClient->putObjectFromStream($bucket, 'stream.txt', fopen('php://temp', 'r+'));
      
  3. Bucket Management

    • Create/Delete Buckets:
      $ossClient->createBucket('my-new-bucket', 'oss-cn-hangzhou');
      $ossClient->deleteBucket('my-new-bucket');
      
    • Bucket ACLs:
      $ossClient->putBucketAcl('my-bucket', 'public-read');
      
  4. Advanced Features

    • Paginators (V2):
      $objects = $ossClient->listObjects($bucket);
      foreach ($objects->getContents() as $object) {
          // Process each object
      }
      
    • Multipart Uploads:
      $uploadId = $ossClient->initMultipartUpload($bucket, 'large-file.zip');
      // Upload parts...
      $ossClient->completeMultipartUpload($bucket, 'large-file.zip', $uploadId, $parts);
      
  5. Integration with Laravel

    • Filesystem Adapter: Use league/flysystem-aliyun-oss for seamless integration with Laravel's Filesystem:
      $adapter = new \League\Flysystem\AwsS3\AwsS3Adapter(
          $ossClient,
          $bucket,
          'oss-cn-hangzhou'
      );
      $filesystem = new \League\Flysystem\Filesystem($adapter);
      
    • Queue Jobs:
      class UploadOssJob implements ShouldQueue
      {
          use Dispatchable, InteractsWithQueue, Queueable;
      
          public function handle()
          {
              $ossClient->putObject($this->bucket, $this->key, $this->filePath);
          }
      }
      

Gotchas and Tips

Pitfalls

  1. V1 vs. V2 Migration

    • V2 is a breaking change. Key differences:
      • Namespace: OSSAlibabacloud\OSS.
      • Method names: putObject()putObjectV2() for progress callbacks.
      • Error handling: V2 uses exceptions (\Alibabacloud\OSS\Exception\OssException).
    • Tip: Use the migration guide and test thoroughly.
  2. CORS and Pre-Signed URLs

    • Pre-signed URLs expire quickly (default: 1 hour). Regenerate dynamically:
      $url = $ossClient->presignObjectUrl($bucket, 'file.txt', time() + 3600); // 1-hour expiry
      
    • Gotcha: Ensure your bucket CORS policy allows the request origin and methods (e.g., GET, PUT).
  3. Retry Logic

    • V2 handles retries automatically, but you can customize:
      $config = new \Alibabacloud\Client\Config([
          'retry' => [
              'max_attempts' => 5,
              'delay' => 100, // ms
          ]
      ]);
      $ossClient = new OssClient($credentials, $endpoint, [], $config);
      
    • Tip: Monitor retries in logs for transient failures (e.g., network issues).
  4. Large File Handling

    • Chunked Uploads: Use multipartUpload for files > 100MB. V2 simplifies this with initMultipartUpload().
    • Memory Limits: Avoid loading entire files into memory. Use streams or chunked reads.
  5. Permissions and Security

    • Least Privilege: Restrict IAM roles to only necessary OSS permissions (e.g., OSS:PutObject).
    • Bucket Policies: Avoid using bucket-level public-read unless required. Use pre-signed URLs or ACLs sparingly.
    • Gotcha: Temporary credentials (STS) are not supported in this SDK. Use IAM users or RAM roles.
  6. Logging and Debugging

    • Enable debug logging for SDK internals:
      $config = new \Alibabacloud\Client\Config([
          'debug' => true,
          'logger' => new \Psr\Log\NullLogger(), // Replace with Monolog/PSR-3 logger
      ]);
      
    • Common Errors:
      • SignatureDoesNotMatch: Check accessKeySecret or request signing.
      • NoSuchBucket: Verify bucket name and region.
      • InvalidAccessKeyId: Confirm accessKeyId is correct.

Tips

  1. Configuration Management

    • Store credentials and endpoints in Laravel's .env:
      OSS_ACCESS_KEY_ID=your-key
      OSS_ACCESS_KEY_SECRET=your-secret
      OSS_ENDPOINT=oss-cn-hangzhou.aliyuncs.com
      OSS_BUCKET=your-bucket
      
    • Use a config file (config/oss.php):
      return [
          'default' => env('OSS_ENDPOINT'),
          'credentials' => [
              'key' => env('OSS_ACCESS_KEY_ID'),
              'secret' => env('OSS_ACCESS_KEY_SECRET'),
          ],
          'buckets' => [
              'primary' => env('OSS_BUCKET'),
          ],
      ];
      
  2. Performance Optimization

    • Parallel Uploads: Use TransmissionManager (V2) for concurrent uploads:
      $transmissionManager = new \Alibabacloud\OSS\Transmission\TransmissionManager($ossClient);
      $uploadTask = $transmissionManager->uploadObject(
          $bucket,
          'file.txt',
          __DIR__ . '/file.txt'
      );
      $uploadTask->wait(); // Block until complete
      
    • CDN Integration: Configure OSS bucket for CDN acceleration via the OSS Console.
  3. Testing

    • Use a staging bucket for testing. Clean up after tests:
      $ossClient->deleteObject($bucket, 'test-file.txt');
      
    • Mock the SDK in unit tests:
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.
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
babelqueue/php-sdk
facebook/capi-param-builder-php
babelqueue/symfony
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver