async-aws/lambda
Async AWS Lambda client for PHP with promise-based async invocations, typed request/response objects, streaming payload support, and credential/region configuration. Lightweight alternative to the AWS SDK for calling and managing Lambda functions.
Installation:
composer require async-aws/lambda
Requires PHP 8.2+ and async-aws/core (installed automatically).
Basic Usage:
use AsyncAws\Lambda\LambdaClient;
$client = new LambdaClient([
'region' => 'us-east-1',
'version' => 'latest',
'credentials' => [
'key' => 'YOUR_ACCESS_KEY',
'secret' => 'YOUR_SECRET_KEY',
],
]);
// Example: List all Lambda functions
$result = $client->listFunctions();
foreach ($result->getFunctions() as $function) {
echo $function->getFunctionName() . "\n";
}
First Use Case: Invoke a Lambda function with payload:
$result = $client->invoke([
'functionName' => 'my-function',
'payload' => json_encode(['key' => 'value']),
]);
echo $result->getPayload(); // Raw response
LambdaClient (main interface for all operations).listFunctions(), getFunction(), invoke(), etc.FunctionConfiguration, LayerVersion).$client->createFunction([
'functionName' => 'my-function',
'runtime' => 'nodejs20.x',
'handler' => 'index.handler',
'role' => 'arn:aws:iam::123456789012:role/lambda-role',
'code' => [
'zipFile' => file_get_contents('function.zip'),
],
]);
$config = $client->getFunctionConfiguration(['functionName' => 'my-function']);
$config->setMemorySize(1024); // Update memory
$client->updateFunctionConfiguration($config);
$result = $client->invoke([
'functionName' => 'my-function',
'payload' => json_encode(['event' => 'data']),
]);
$client->invokeAsync([
'functionName' => 'my-function',
'payload' => json_encode(['event' => 'data']),
]);
$result = $client->invokeWithResponseStream([
'functionName' => 'my-function',
'payload' => json_encode(['event' => 'data']),
]);
$client->publishLayerVersion([
'layerName' => 'my-layer',
'content' => [
'zipFile' => file_get_contents('layer.zip'),
],
]);
$client->addPermission([
'functionName' => 'my-function',
'action' => 'lambda:InvokeFunction',
'principal' => 'arn:aws:iam::123456789012:user/alice',
]);
$client->createEventSourceMapping([
'eventSourceArn' => 'arn:aws:sqs:us-east-1:123456789012:my-queue',
'functionName' => 'my-function',
'batchSize' => 10,
]);
$client->putFunctionConcurrency([
'functionName' => 'my-function',
'reservedConcurrentExecutions' => 10,
]);
Register the client in AppServiceProvider:
use AsyncAws\Lambda\LambdaClient;
public function register()
{
$this->app->singleton(LambdaClient::class, function ($app) {
return new LambdaClient([
'region' => config('aws.region'),
'credentials' => [
'key' => config('aws.key'),
'secret' => config('aws.secret'),
],
]);
});
}
Inject the client into controllers/services:
use AsyncAws\Lambda\LambdaClient;
class MyService {
public function __construct(private LambdaClient $lambda) {}
public function process()
{
$this->lambda->invoke([...]);
}
}
Use try-catch for AWS-specific exceptions:
use AsyncAws\Core\Exception\AwsException;
try {
$client->invoke([...]);
} catch (AwsException $e) {
logger()->error('Lambda error: ' . $e->getAwsErrorMessage());
throw new \RuntimeException('Lambda invocation failed', 0, $e);
}
For non-blocking calls (e.g., in queues), use invokeAsync and handle responses via SQS/SNS or CloudWatch Logs.
Region Configuration:
us-isob-west-1 for AWS GovCloud (ISO) regions.us-isof-east-1).Payload Size Limits:
Invoke has a 6MB payload limit (use InvokeWithResponseStream for larger payloads).CreateFunction has a 50MB zip limit (use S3 for larger deployments).Concurrency Quotas:
PutFunctionConcurrency to reserve slots for critical functions.VPC Encryption Controls:
DisallowedByVpcEncryptionControl is handled in error responses (e.g., LastUpdateStatusReasonCode).Runtime Compatibility:
nodejs20.x, python3.12). Check changelog for updates.Special Characters in Names:
# (e.g., my-function#prod) require proper escaping in the functionName parameter.Enable Debug Logging:
$client = new LambdaClient([
'debug' => true, // Enable debug logs
// ... other config
]);
Logs appear in storage/logs/laravel.log (Laravel) or stdout.
Validate Inputs:
json_encode() to validate payloads before invoking:
$payload = json_encode(['event' => 'data']);
if (json_last_error() !== JSON_ERROR_NONE) {
throw new \InvalidArgumentException('Invalid payload');
}
Check Response Metadata:
$result = $client->invoke([...]);
$headers = $result->getHeaders(); // Inspect raw headers
Retry Transient Errors:
TooManyRequestsException):
use AsyncAws\Core\Exception\AwsException;
$attempts = 0;
$maxAttempts = 3;
do {
try {
return $client->invoke([...]);
} catch (AwsException $e) {
if ($e->getAwsErrorCode() === 'TooManyRequestsException' && $attempts < $maxAttempts) {
sleep(2 ** $attempts); // Exponential backoff
$attempts++;
} else {
throw $e;
}
}
} while (true);
Custom Middleware:
AsyncAws\Core\Middleware\MiddlewareStack to add logging/auditing:
use AsyncAws\Core\Middleware\MiddlewareStack;
use AsyncAws\Core\Request;
$stack = new MiddlewareStack();
$stack->push(function (Request $request) {
logger()->info('Lambda request:', ['action' => $request->getAction()]);
});
$client = new LambdaClient(['middleware' => $stack]);
Event Subscribers:
function:created) using AWS EventBridge or CloudWatch Events.Local Testing:
localstack or aws-lambda-ric for local development:
$client = new
How can I help you explore Laravel packages today?