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

S3 Laravel Package

async-aws/s3

AsyncAws S3 is a lightweight, async-friendly PHP client for Amazon S3. Install via Composer and interact with S3 using the AsyncAws ecosystem, with CI/BC checks and full docs available at async-aws.com.

View on GitHub
Deep Wiki
Context7
## Getting Started

### Minimal Setup
1. **Installation**:
   ```bash
   composer require async-aws/s3

Requires PHP 8.2+ and Laravel 9+ (or standalone usage).

  1. Basic Client Initialization:

    use AsyncAws\S3\S3Client;
    
    $client = new S3Client([
        'region' => 'us-east-1',
        'version' => 'latest',
        'credentials' => [
            'key'    => env('AWS_ACCESS_KEY_ID'),
            'secret' => env('AWS_SECRET_ACCESS_KEY'),
        ],
    ]);
    
  2. First Use Case: Upload a File

    $result = $client->putObject([
        'Bucket' => 'my-bucket',
        'Key'    => 'path/to/file.txt',
        'Body'   => fopen('local-file.txt', 'r'),
    ]);
    
  3. Where to Look First:

    • Official Documentation
    • AsyncAws\S3\S3Client class (core methods)
    • AsyncAws\S3\Input\* and AsyncAws\S3\Result\* namespaces (request/response objects)

Implementation Patterns

Core Workflows

1. File Operations

  • Upload:
    $client->putObject([
        'Bucket' => 'my-bucket',
        'Key'    => 'file.jpg',
        'Body'   => fopen('image.jpg', 'r'),
        'Metadata' => ['author' => 'John Doe'],
    ]);
    
  • Download:
    $result = $client->getObject([
        'Bucket' => 'my-bucket',
        'Key'    => 'file.jpg',
    ]);
    file_put_contents('local-file.jpg', $result->getBody()->getContents());
    
  • Streaming Download (for large files):
    $result = $client->getObject(['Bucket' => 'my-bucket', 'Key' => 'large-file.zip']);
    $result->getBody()->pipe($outputStream); // Stream directly to another location
    

2. Bucket Management

  • Create/Delete:
    $client->createBucket(['Bucket' => 'new-bucket']);
    $client->deleteBucket(['Bucket' => 'empty-bucket']);
    
  • List Buckets:
    $buckets = $client->listBuckets()->getBuckets();
    

3. Multipart Uploads (for large files)

// Initiate
$uploadId = $client->createMultipartUpload([
    'Bucket' => 'my-bucket',
    'Key'    => 'large-file.zip',
])->getUploadId();

// Upload parts
$parts = [];
foreach (range(1, 10) as $partNumber) {
    $result = $client->uploadPart([
        'Bucket' => 'my-bucket',
        'Key'    => 'large-file.zip',
        'PartNumber' => $partNumber,
        'UploadId' => $uploadId,
        'Body' => fopen("part-$partNumber.dat", 'r'),
    ]);
    $parts[] = $result->getPart();
}

// Complete
$client->completeMultipartUpload([
    'Bucket' => 'my-bucket',
    'Key'    => 'large-file.zip',
    'UploadId' => $uploadId,
    'MultipartUpload' => ['Parts' => $parts],
]);

4. Lifecycle and Versioning

  • Enable Versioning:
    $client->putBucketVersioning([
        'Bucket' => 'my-bucket',
        'VersioningConfiguration' => ['Status' => 'Enabled'],
    ]);
    
  • Set Lifecycle Rules:
    $client->putBucketLifecycleConfiguration([
        'Bucket' => 'my-bucket',
        'LifecycleConfiguration' => [
            'Rules' => [
                [
                    'ID' => 'rule1',
                    'Status' => 'Enabled',
                    'Filter' => ['Prefix' => 'logs/'],
                    'Transitions' => [
                        ['StorageClass' => 'GLACIER', 'Days' => 30],
                    ],
                ],
            ],
        ],
    ]);
    

5. Presigned URLs (for temporary access)

$presignedUrl = $client->getObjectUrl(
    'my-bucket',
    'file.jpg',
    '+1 hour' // Expiry time
);

6. Integration with Laravel

  • Service Provider:
    use AsyncAws\S3\S3Client;
    
    class S3ServiceProvider extends ServiceProvider {
        public function register() {
            $this->app->singleton(S3Client::class, function ($app) {
                return new S3Client([
                    'region' => config('aws.region'),
                    'credentials' => [
                        'key'    => config('aws.key'),
                        'secret' => config('aws.secret'),
                    ],
                ]);
            });
        }
    }
    
  • Facade:
    use Illuminate\Support\Facades\Facade;
    
    class S3Facade extends Facade {
        protected static function getFacadeAccessor() {
            return S3Client::class;
        }
    }
    
  • Usage in Controllers:
    use App\Facades\S3;
    
    public function upload() {
        $result = S3::putObject([...]);
    }
    

7. Error Handling

try {
    $client->getObject(['Bucket' => 'my-bucket', 'Key' => 'nonexistent.txt']);
} catch (\AsyncAws\Core\Exception\S3Exception $e) {
    if ($e->getAwsErrorCode() === 'NoSuchKey') {
        // Handle missing file
    }
}

Gotchas and Tips

Pitfalls

  1. Region Configuration:

    • Always specify the correct region. Some operations (e.g., createBucket) require LocationConstraint for non-us-east-1 regions.
    • Example:
      $client->createBucket([
          'Bucket' => 'my-bucket',
          'CreateBucketConfiguration' => ['LocationConstraint' => 'eu-west-1'],
      ]);
      
  2. Path vs. Virtual Hosted-Style Endpoints:

    • By default, AsyncAws uses virtual hosted-style endpoints (e.g., https://bucket.s3.amazonaws.com). To use path-style (e.g., https://s3.amazonaws.com/bucket), set:
      $client = new S3Client(['s3PathStyleEndpoint' => true]);
      
  3. Metadata Handling:

    • Metadata keys are case-sensitive and must not include the x-amz-meta- prefix when setting. AsyncAws handles this internally.
    • Example:
      // Correct
      $client->putObject([
          'Bucket' => 'my-bucket',
          'Key' => 'file.txt',
          'Metadata' => ['author' => 'John Doe'], // No prefix
      ]);
      
  4. Large File Uploads:

    • For files > 100MB, use multipart uploads. AsyncAws supports this out of the box with the createMultipartUpload, uploadPart, and completeMultipartUpload methods.
    • Ensure your local parts are correctly aligned with AWS's part size limits (5MB–5GB per part).
  5. CORS Configuration:

    • When setting CORS rules, ensure the AllowedHeaders, AllowedMethods, and ExposeHeaders are correctly formatted as arrays.
    • Example:
      $client->putBucketCors([
          'Bucket' => 'my-bucket',
          'CORSConfiguration' => [
              'CORSRules' => [
                  [
                      'AllowedHeaders' => ['*'],
                      'AllowedMethods' => ['GET', 'PUT', 'POST', 'DELETE'],
                      'AllowedOrigins' => ['https://example.com'],
                      'ExposeHeaders' => ['ETag'],
                  ],
              ],
          ],
      ]);
      
  6. Presigned URLs:

    • Presigned URLs are not cached by default. If you need caching, implement it on your side (e.g., Redis).
    • Example expiry formats:
      // Relative time
      $url = $client->getObjectUrl('bucket', 'key', '+1 hour');
      
      // Absolute time (DateTimeImmutable)
      $url = $client->getObjectUrl('bucket', 'key', new \DateTimeImmutable('+1 hour'));
      
  7. Concurrency and Retries:

    • AsyncAws uses Guzzle under the hood, which supports retries. Configure retry logic via:
      $client = new S3Client([
          'retry' => [
              'max_attempts' => 3,
              'delay' => 100, // ms
          ],
      ]);
      
  8. **PHP 8.2+

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.
codraw/framework-extra-bundle
codraw/messenger
codraw/security
codraw/mailer
codraw/contracts
codraw/profiling
codraw/dependency-injection
codraw/tester
codraw/core
nexmo/api-specification
capell-app/block-library
axium/identity
cetria/laravel-dummy-models
cetria/reflection-helper
agropredict/sso-auth-bundle
evolvestudio/spam-protection
datacore/hub-sdk
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony