async-aws/dynamo-db
AsyncAws DynamoDb is a lightweight PHP client for Amazon DynamoDB, designed for AsyncAws. Install via Composer and use it to perform DynamoDB operations with a modern API. Full documentation and contribution guidelines available at async-aws.com.
Installation
composer require async-aws/dynamo-db
Ensure aws/aws-sdk-php is also installed (dependency).
Basic Client Initialization
use AsyncAws\DynamoDb\DynamoDbClient;
$client = new DynamoDbClient([
'region' => 'us-east-1',
'version' => 'latest',
'credentials' => [
'key' => env('AWS_ACCESS_KEY_ID'),
'secret' => env('AWS_SECRET_ACCESS_KEY'),
],
]);
First Use Case: Query a Table
$result = $client->query([
'TableName' => 'Users',
'KeyConditionExpression' => 'id = :id',
'ExpressionAttributeValues' => [':id' => ['S' => '123']],
]);
src/ for core classes (DynamoDbClient, Command, Model).tests/ directory) for usage examples and edge cases.Leverage the Command facade for fluent, chainable operations:
use AsyncAws\DynamoDb\Command\GetItem;
use AsyncAws\DynamoDb\Command\PutItem;
$getItem = new GetItem('Users', ['id' => ['S' => '123']]);
$item = $client->getItem($getItem);
$putItem = new PutItem('Users', [
'id' => ['S' => '123'],
'name' => ['S' => 'John Doe'],
]);
$client->putItem($putItem);
Use BatchWriteItem for bulk inserts/updates/deletes:
$batchWrite = new BatchWriteItem([
'RequestItems' => [
'Users' => [
new PutRequest(['id' => ['S' => '456'], 'name' => ['S' => 'Jane Smith']]),
new DeleteRequest(['id' => ['S' => '789']]),
],
],
]);
$client->batchWriteItem($batchWrite);
For multi-table atomic operations:
$transactWrite = new TransactWrite([
'TransactItems' => [
new TransactPut(['TableName' => 'Users', 'Item' => [...]]),
new TransactUpdate(['TableName' => 'Orders', 'Update' => [...]]),
],
]);
$client->transactWriteItems($transactWrite);
Handle large result sets with LastEvaluatedKey:
$lastKey = null;
do {
$query = new Query('Users', 'id', ['S' => '123'], $lastKey);
$result = $client->query($query);
$lastKey = $result->getLastEvaluatedKey();
} while ($lastKey);
$this->app->singleton(DynamoDbClient::class, function ($app) {
return new DynamoDbClient($app['config']['aws']);
});
class UserModel extends \AsyncAws\DynamoDb\Model {
protected $table = 'Users';
protected $primaryKey = 'id';
}
Attribute Value Formatting
DynamoDB requires strict typing (e.g., ['S' => 'string'] for strings).
Fix: Use AttributeValue helper or validate inputs:
$client->putItem(new PutItem('Users', [
'id' => AttributeValue::fromString('123'),
'metadata' => AttributeValue::fromMap(['key' => 'value']),
]));
Throttling
DynamoDB enforces provisioned throughput.
Fix: Implement exponential backoff or use ProvisionedThroughputExceededException handling:
try {
$client->query($query);
} catch (ProvisionedThroughputExceededException $e) {
sleep(1); // Retry after delay
}
Case Sensitivity Table/attribute names are case-sensitive in DynamoDB. Tip: Use constants or config for names:
class DynamoDbTables {
public const USERS = 'Users';
}
Async vs. Sync
The package supports async operations (e.g., Promise integration).
Tip: Use await for async calls:
$result = await($client->query($query));
putenv('AWS_DEBUG=1');
$client->setHandlerStack(new HandlerStack([
new \Aws\Common\Credential\CredentialProviderChain(),
new \Aws\Common\Middleware\LoggerMiddleware(
new \Monolog\Logger('DynamoDb')
)
]));
Custom Middleware Add middleware to the handler stack for logging/auditing:
$client->getHandlerStack()->push(new class implements Middleware {
public function __invoke($request, $handler) {
// Pre-process request
$response = $handler->handle($request);
// Post-process response
return $response;
}
});
Event Dispatching Trigger events on CRUD operations (e.g., via Laravel Events):
event(new UserCreated($item));
Repository Pattern Abstract DynamoDB operations into repositories:
class UserRepository {
public function __construct(private DynamoDbClient $client) {}
public function findById(string $id): array {
return $this->client->getItem(new GetItem('Users', ['id' => ['S' => $id]]));
}
}
$client->query($query, ['region' => 'eu-west-1']);
$client = new DynamoDbClient(['endpoint' => 'http://localhost:8000']);
How can I help you explore Laravel packages today?