async-aws/core
AsyncAws Core provides the shared foundation for AsyncAws AWS clients, including request signing, HTTP utilities, configuration and credential handling. Also includes an STS client for authentication. Install via composer and build AWS integrations with a lightweight SDK.
## Getting Started
### Minimal Setup
1. **Installation**:
```bash
composer require async-aws/core
Requires PHP 8.2+ and Symfony HTTP Client (or Guzzle).
Basic Usage:
use AsyncAws\Core\AwsClientFactory;
use AsyncAws\Core\Credential\CredentialProvider;
// Load credentials from default AWS config (~/.aws/credentials)
$credentialProvider = CredentialProvider::createDefault();
// Create a client factory
$clientFactory = new AwsClientFactory($credentialProvider);
// Use the factory to create clients (e.g., STS)
$stsClient = $clientFactory->sts();
First Use Case: Assume a role using STS:
$result = $stsClient->assumeRole([
'RoleArn' => 'arn:aws:iam::123456789012:role/MyRole',
'RoleSessionName' => 'MySession'
]);
$credentials = $result->getCredentials();
AwsClientFactory: Central hub for creating AWS service clients (STS, S3, etc.).CredentialProvider: Manages AWS credentials (supports profiles, SSO, environment variables).Configuration: Configures clients (region, endpoint, debug mode).Dynamic Client Creation:
Use AwsClientFactory to instantiate clients dynamically:
$clientFactory = new AwsClientFactory($credentialProvider);
$s3Client = $clientFactory->s3(); // Requires `async-aws/s3` package
$ec2Client = $clientFactory->ec2(); // Requires `async-aws/ec2` package
Custom Endpoints: Override default endpoints (e.g., for localstack):
$configuration = new Configuration([
'endpoint' => 'http://localhost:4566',
'region' => 'us-east-1',
]);
$clientFactory = new AwsClientFactory($credentialProvider, $configuration);
Region Handling:
Use @region in input objects for multi-region operations:
$result = $s3Client->getObject([
'@region' => 'eu-west-1',
'Bucket' => 'my-bucket',
'Key' => 'file.txt',
]);
SSO Support:
Configure SSO credentials via SsoOidcProvider:
$ssoProvider = new SsoOidcProvider(
'https://my-sso-portal.awsapps.com/start',
'my-account-id',
'my-role-name'
);
$credentialProvider = new CredentialProvider($ssoProvider);
Environment Variables: Fallback to environment variables if no profile is specified:
putenv('AWS_ACCESS_KEY_ID=AKIA...');
putenv('AWS_SECRET_ACCESS_KEY=...');
putenv('AWS_DEFAULT_REGION=us-east-1');
Credential Caching: Cache credentials to avoid repeated STS calls:
$cache = new SymfonyCacheProvider(new FilesystemCache('/tmp/aws_cache'));
$credentialProvider = new CredentialProvider($cache);
Presigned URLs: Generate presigned URLs for S3 objects:
$presignedUrl = $s3Client->presign('getObject', [
'Bucket' => 'my-bucket',
'Key' => 'file.txt',
'Expires' => '+1 hour',
]);
Streaming Responses: Handle large responses efficiently:
$result = $s3Client->getObject(['Bucket' => 'my-bucket', 'Key' => 'large-file.zip']);
$stream = $result->getBody();
while ($chunk = $stream->read()) {
// Process chunk
}
Retryable Clients: Configure retry logic for transient failures:
$httpClient = $clientFactory->createHttpClient([
'retryable_status_codes' => [429, 500, 502, 503, 504],
]);
Mock Responses:
Use ResultMockFactory for unit testing:
$mockFactory = new ResultMockFactory();
$mockResult = $mockFactory->createSuccess([
'Credentials' => [
'AccessKeyId' => 'AKIA...',
'SecretAccessKey' => '...',
'SessionToken' => '...',
],
]);
$stsClient->assumeRole(...)->willReturn($mockResult);
Failing Responses: Simulate AWS errors:
$mockFactory->createFailing(
new ClientException('InvalidAccessKeyId', 403, [], 'RequestId:...')
);
Custom Exceptions:
Map AWS error codes to custom exceptions via RequestContext:
$context = new RequestContext();
$context->addErrorMapping('InvalidAccessKeyId', InvalidCredentialsException::class);
$result = $s3Client->getObject([...], $context);
Debugging: Enable debug logging:
$configuration = new Configuration(['debug' => true]);
Region Mismatch:
Configuration matches the region in the AWS service.@region in input objects for dynamic region switching.Credential Expiry:
$credentials = $result->getCredentials();
if ($credentials->isExpired()) {
$credentials = $stsClient->getSessionToken()->getCredentials();
}
Chunked Requests:
sendChunkedBody: false).'sendChunkedBody' => true in Configuration if required.SSO Dependencies:
async-aws/sso-oidc and league/oauth2-client.composer require async-aws/sso-oidc league/oauth2-client
Endpoint Discovery:
%region% or %service% placeholders (deprecated in v2.0).'endpoint' => 'https://s3.us-east-1.amazonaws.com').PHP 8.5+ Deprecations:
null as an array offset (e.g., $array[null]).isset($array['key']) or array_key_exists().Thread Safety:
SymfonyCacheProvider) for shared environments.Large Responses:
ResponseBodyStream) may fail if the underlying stream is closed prematurely.$configuration = new Configuration(['buffer_response' => true]);
Enable Debug Mode:
$configuration = new Configuration(['debug' => true]);
Logs HTTP requests/responses to stderr.
Inspect Raw Responses:
Use getResponse() to access the underlying Psr\Http\Message\Response:
$response = $result->getResponse();
$body = (string) $response->getBody();
Validate Inputs:
Use Input::validate() to check input objects before sending requests:
use AsyncAws\Core\Input;
$input = new Input(['Bucket' => 'my-bucket', 'Key' => 'file.txt']);
$input->validate();
Check for Deprecated Methods:
getEndpointMetadata() are deprecated in v2.0. Use getEndpoint() instead.Reuse Clients: Instantiate clients once and reuse them (e.g., in a service container):
$container->bind(AwsClientFactory::class, function () {
return new AwsClientFactory(CredentialProvider::createDefault());
});
Batch Operations:
Use pagination and batching where possible (e.g., ListObjectsV2 with MaxKeys).
Disable Retries for Idempotent Operations: Reduce latency for safe operations:
$
How can I help you explore Laravel packages today?