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

Aws Sdk For Php Laravel Package

amazonwebservices/aws-sdk-for-php

Official AWS SDK for PHP. Build PHP apps that integrate with Amazon Web Services, including S3, DynamoDB, SNS/SQS, CloudWatch, Lambda and more. Supports modern auth/signing, retries, pagination, and async operations.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation Add the package via Composer (note: deprecated, but may still be used in legacy projects):

    composer require amazonwebservices/aws-sdk-for-php:^1.0
    

    Verify vendor/aws/aws-sdk-php exists in your project.

  2. First Use Case: S3 File Upload Initialize the SDK in config/services.php:

    'aws' => [
        'key'    => env('AWS_ACCESS_KEY_ID'),
        'secret' => env('AWS_SECRET_ACCESS_KEY'),
        'region' => env('AWS_DEFAULT_REGION', 'us-east-1'),
    ],
    

    Use in a controller:

    use Aws\S3\S3Client;
    
    $s3 = new S3Client([
        'version' => 'latest',
        'region'  => config('services.aws.region'),
        'credentials' => [
            'key'    => config('services.aws.key'),
            'secret' => config('services.aws.secret'),
        ]
    ]);
    
    $s3->putObject([
        'Bucket' => 'your-bucket',
        'Key'    => 'file.txt',
        'Body'   => fopen('local-file.txt', 'r')
    ]);
    
  3. Key Files to Review

    • vendor/aws/aws-sdk-php/src/Aws (core classes)
    • vendor/aws/aws-sdk-php/examples (legacy examples)
    • config/services.php (credentials setup)

Implementation Patterns

Common Workflows

  1. Service Integration Use dependency injection for AWS services:

    // app/Providers/AppServiceProvider.php
    public function register()
    {
        $this->app->singleton(S3Client::class, function ($app) {
            return new S3Client($app['config']['services.aws']);
        });
    }
    

    Inject into controllers:

    public function __construct(S3Client $s3) {
        $this->s3 = $s3;
    }
    
  2. Async Operations Use promises for long-running tasks (e.g., batch processing):

    $promise = $s3->registerBucket([
        'Bucket' => 'new-bucket',
        'CreateBucketConfiguration' => ['LocationConstraint' => 'us-west-2']
    ]);
    
    $promise->then(function ($result) {
        // Handle success
    })->wait();
    
  3. Error Handling Centralize AWS exceptions in a middleware:

    // app/Exceptions/Handler.php
    public function render($request, Throwable $exception)
    {
        if ($exception instanceof Aws\AwsException) {
            return response()->json([
                'error' => 'AWS Service Error',
                'code'  => $exception->getAwsErrorCode(),
                'message' => $exception->getMessage()
            ], 500);
        }
        return parent::render($request, $exception);
    }
    
  4. Configuration Management Extend Aws\Common\Credentials\CredentialsInterface for dynamic credentials:

    class TemporaryCredentials extends CredentialsInterface {
        public function getCredentials() {
            return [
                'key'    => env('TEMP_AWS_KEY'),
                'secret' => env('TEMP_AWS_SECRET'),
            ];
        }
    }
    

    Use in SDK initialization:

    $s3 = new S3Client([
        'credentials' => new TemporaryCredentials()
    ]);
    

Gotchas and Tips

Pitfalls

  1. Deprecation Warnings

    • This package is archived (last release: 2015). Prefer aws/aws-sdk-php (v3+) for new projects.
    • Common deprecation triggers:
      • Aws\Common\Exception\ExceptionInterface (use Aws\Exception\AwsException in v3).
      • Aws\Common\Credentials\ChainCredentials (replaced by Aws\Credentials\Credentials in v3).
  2. Region-Specific Quirks

    • Hardcoded region checks (e.g., us-east-1 defaults) may cause issues in non-US regions.
    • Workaround: Explicitly set LocationConstraint for buckets:
      $s3->createBucket([
          'Bucket' => 'my-bucket',
          'CreateBucketConfiguration' => ['LocationConstraint' => 'eu-west-1']
      ]);
      
  3. Memory Limits

    • Large file operations (e.g., getObject) may hit PHP’s memory_limit.
    • Mitigate with streaming:
      $result = $s3->getObject([
          'Bucket' => 'bucket',
          'Key'    => 'large-file.zip'
      ]);
      $stream = $result['Body'];
      file_put_contents('local-file.zip', $stream);
      
  4. Credential Caching

    • Static credentials (e.g., ChainCredentials) are not cached by default.
    • Implement Aws\Common\Credentials\CredentialsInterface with caching logic:
      class CachedCredentials implements CredentialsInterface {
          private $credentials;
          private $ttl;
      
          public function __construct($credentials, $ttl = 3600) {
              $this->credentials = $credentials;
              $this->ttl = $ttl;
          }
      
          public function getCredentials() {
              return $this->credentials; // Add TTL logic here
          }
      }
      

Debugging Tips

  1. Enable Debugging Use the Aws\Common\Logger\LoggerChain to log requests/responses:

    use Aws\Common\Logger\LoggerChain;
    use Aws\Common\Logger\StreamHandler;
    
    $logger = new LoggerChain([
        new StreamHandler(fopen('php://stdout', 'w'), LoggerInterface::DEBUG)
    ]);
    
    $s3 = new S3Client([
        'logger' => $logger,
        // ... other config
    ]);
    
  2. Common Errors & Fixes

    Error Cause Solution
    InvalidAccessKeyId Wrong credentials Verify AWS_ACCESS_KEY_ID in .env
    SignatureDoesNotMatch Expired/incorrect secret Regenerate AWS_SECRET_ACCESS_KEY
    NoSuchBucket Bucket doesn’t exist Check region/bucket name case sensitivity
    RequestTimeout Slow network/large payload Increase timeout in SDK config
  3. Testing

    • Use Aws\Common\Credentials\CredentialsInterface mocks in PHPUnit:
      $mockCredentials = $this->createMock(CredentialsInterface::class);
      $mockCredentials->method('getCredentials')->willReturn([
          'key'    => 'test-key',
          'secret' => 'test-secret'
      ]);
      
      $s3 = new S3Client([
          'credentials' => $mockCredentials,
          'region'      => 'us-east-1',
          'version'     => 'latest'
      ]);
      
    • Mock entire services with Aws\Common\ServiceAbstract:
      $mockS3 = $this->getMockBuilder(S3Client::class)
          ->disableOriginalConstructor()
          ->onlyMethods(['putObject'])
          ->getMock();
      
      $mockS3->expects($this->once())
          ->method('putObject')
          ->with(['Bucket' => 'test', 'Key' => 'file.txt']);
      

Extension Points

  1. Custom Middleware Extend Aws\Common\Middleware\MiddlewareStack to add pre/post-processing:

    class LoggingMiddleware implements MiddlewareInterface {
        public function __invoke($request, $handler) {
            // Log request
            $response = $handler($request);
            // Log response
            return $response;
        }
    }
    

    Register in SDK:

    $s3 = new S3Client([
        'middleware' => [
            new LoggingMiddleware(),
            // ... other middleware
        ]
    ]);
    
  2. Plugin System Use Aws\Common\Plugin\PluginInterface to extend functionality:

    class CustomPlugin implements PluginInterface {
        public function register(Aws\Common\Aws $aws) {
            $aws->register('customService', function () {
                return new CustomService();
            });
        }
    }
    

    Attach to SDK:

    $s3 = new S3Client([
        'plugins' => [new CustomPlugin()]
    ]);
    
  3. Legacy Migration Helper For transitioning to v3, create a wrapper class:

    class V1ToV3Adapter {
        private $v3Client;
    
        public function __construct($config) {
            $this->v3Client = new Aws\S3\S3Client($config);
        }
    
        public function putObject($params) {
            return $this->v3Client->putObject($params);
        }
    
        // Delegate other methods...
    }
    
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