使用适用于 PHP 的 SDK 的 Lambda 示例 - Amazon SDK for PHP
Amazon Web Services 文档中描述的 Amazon Web Services 服务或功能可能因区域而异。要查看适用于中国区域的差异,请参阅 中国的 Amazon Web Services 服务入门 (PDF)

本文属于机器翻译版本。若本译文内容与英语原文存在差异,则一律以英文原文为准。

使用适用于 PHP 的 SDK 的 Lambda 示例

以下代码示例向您展示了如何使用 with Lambda 来执行操作和实现常见场景。 Amazon SDK for PHP

操作是大型程序的代码摘录,必须在上下文中运行。您可以通过操作了解如何调用单个服务函数,还可以通过函数相关场景和跨服务示例的上下文查看操作。

场景是展示如何通过在同一服务中调用多个函数来完成特定任务任务的代码示例。

每个示例都包含一个指向的链接 GitHub,您可以在其中找到有关如何在上下文中设置和运行代码的说明。

操作

以下代码示例演示如何使用 CreateFunction

适用于 PHP 的 SDK
注意

还有更多相关信息 GitHub。在 Amazon 代码示例存储库中查找完整实例,了解如何进行设置和运行。

public function createFunction($functionName, $role, $bucketName, $handler) { //This assumes the Lambda function is in an S3 bucket. return $this->customWaiter(function () use ($functionName, $role, $bucketName, $handler) { return $this->lambdaClient->createFunction([ 'Code' => [ 'S3Bucket' => $bucketName, 'S3Key' => $functionName, ], 'FunctionName' => $functionName, 'Role' => $role['Arn'], 'Runtime' => 'python3.9', 'Handler' => "$handler.lambda_handler", ]); }); }
  • 有关 API 的详细信息,请参阅 Amazon SDK for PHP API 参考CreateFunction中的。

以下代码示例演示如何使用 DeleteFunction

适用于 PHP 的 SDK
注意

还有更多相关信息 GitHub。在 Amazon 代码示例存储库中查找完整实例,了解如何进行设置和运行。

public function deleteFunction($functionName) { return $this->lambdaClient->deleteFunction([ 'FunctionName' => $functionName, ]); }
  • 有关 API 的详细信息,请参阅 Amazon SDK for PHP API 参考DeleteFunction中的。

以下代码示例演示如何使用 GetFunction

适用于 PHP 的 SDK
注意

还有更多相关信息 GitHub。在 Amazon 代码示例存储库中查找完整实例,了解如何进行设置和运行。

public function getFunction($functionName) { return $this->lambdaClient->getFunction([ 'FunctionName' => $functionName, ]); }
  • 有关 API 的详细信息,请参阅 Amazon SDK for PHP API 参考GetFunction中的。

以下代码示例演示如何使用 Invoke

适用于 PHP 的 SDK
注意

还有更多相关信息 GitHub。在 Amazon 代码示例存储库中查找完整实例,了解如何进行设置和运行。

public function invoke($functionName, $params, $logType = 'None') { return $this->lambdaClient->invoke([ 'FunctionName' => $functionName, 'Payload' => json_encode($params), 'LogType' => $logType, ]); }
  • 有关 API 详细信息,请参阅《Amazon SDK for PHP API 参考》中的 Invoke

以下代码示例演示如何使用 ListFunctions

适用于 PHP 的 SDK
注意

还有更多相关信息 GitHub。在 Amazon 代码示例存储库中查找完整实例,了解如何进行设置和运行。

public function listFunctions($maxItems = 50, $marker = null) { if (is_null($marker)) { return $this->lambdaClient->listFunctions([ 'MaxItems' => $maxItems, ]); } return $this->lambdaClient->listFunctions([ 'Marker' => $marker, 'MaxItems' => $maxItems, ]); }
  • 有关 API 的详细信息,请参阅 Amazon SDK for PHP API 参考ListFunctions中的。

以下代码示例演示如何使用 UpdateFunctionCode

适用于 PHP 的 SDK
注意

还有更多相关信息 GitHub。在 Amazon 代码示例存储库中查找完整实例,了解如何进行设置和运行。

public function updateFunctionCode($functionName, $s3Bucket, $s3Key) { return $this->lambdaClient->updateFunctionCode([ 'FunctionName' => $functionName, 'S3Bucket' => $s3Bucket, 'S3Key' => $s3Key, ]); }
  • 有关 API 的详细信息,请参阅 Amazon SDK for PHP API 参考UpdateFunctionCode中的。

以下代码示例演示如何使用 UpdateFunctionConfiguration

适用于 PHP 的 SDK
注意

还有更多相关信息 GitHub。在 Amazon 代码示例存储库中查找完整实例,了解如何进行设置和运行。

public function updateFunctionConfiguration($functionName, $handler, $environment = '') { return $this->lambdaClient->updateFunctionConfiguration([ 'FunctionName' => $functionName, 'Handler' => "$handler.lambda_handler", 'Environment' => $environment, ]); }

场景

以下代码示例展示了如何:

  • 创建 IAM 角色和 Lambda 函数,然后上传处理程序代码。

  • 使用单个参数来调用函数并获取结果。

  • 更新函数代码并使用环境变量进行配置。

  • 使用新参数来调用函数并获取结果。显示返回的执行日志。

  • 列出账户函数,然后清除函数。

有关更多信息,请参阅使用控制台创建 Lambda 函数

适用于 PHP 的 SDK
注意

还有更多相关信息 GitHub。在 Amazon 代码示例存储库中查找完整示例,了解如何进行设置和运行。

namespace Lambda; use Aws\S3\S3Client; use GuzzleHttp\Psr7\Stream; use Iam\IAMService; class GettingStartedWithLambda { public function run() { echo("\n"); echo("--------------------------------------\n"); print("Welcome to the AWS Lambda getting started demo using PHP!\n"); echo("--------------------------------------\n"); $clientArgs = [ 'region' => 'us-west-2', 'version' => 'latest', 'profile' => 'default', ]; $uniqid = uniqid(); $iamService = new IAMService(); $s3client = new S3Client($clientArgs); $lambdaService = new LambdaService(); echo "First, let's create a role to run our Lambda code.\n"; $roleName = "test-lambda-role-$uniqid"; $rolePolicyDocument = "{ \"Version\": \"2012-10-17\", \"Statement\": [ { \"Effect\": \"Allow\", \"Principal\": { \"Service\": \"lambda.amazonaws.com\" }, \"Action\": \"sts:AssumeRole\" } ] }"; $role = $iamService->createRole($roleName, $rolePolicyDocument); echo "Created role {$role['RoleName']}.\n"; $iamService->attachRolePolicy( $role['RoleName'], "arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole" ); echo "Attached the AWSLambdaBasicExecutionRole to {$role['RoleName']}.\n"; echo "\nNow let's create an S3 bucket and upload our Lambda code there.\n"; $bucketName = "test-example-bucket-$uniqid"; $s3client->createBucket([ 'Bucket' => $bucketName, ]); echo "Created bucket $bucketName.\n"; $functionName = "doc_example_lambda_$uniqid"; $codeBasic = __DIR__ . "/lambda_handler_basic.zip"; $handler = "lambda_handler_basic"; $file = file_get_contents($codeBasic); $s3client->putObject([ 'Bucket' => $bucketName, 'Key' => $functionName, 'Body' => $file, ]); echo "Uploaded the Lambda code.\n"; $createLambdaFunction = $lambdaService->createFunction($functionName, $role, $bucketName, $handler); // Wait until the function has finished being created. do { $getLambdaFunction = $lambdaService->getFunction($createLambdaFunction['FunctionName']); } while ($getLambdaFunction['Configuration']['State'] == "Pending"); echo "Created Lambda function {$getLambdaFunction['Configuration']['FunctionName']}.\n"; sleep(1); echo "\nOk, let's invoke that Lambda code.\n"; $basicParams = [ 'action' => 'increment', 'number' => 3, ]; /** @var Stream $invokeFunction */ $invokeFunction = $lambdaService->invoke($functionName, $basicParams)['Payload']; $result = json_decode($invokeFunction->getContents())->result; echo "After invoking the Lambda code with the input of {$basicParams['number']} we received $result.\n"; echo "\nSince that's working, let's update the Lambda code.\n"; $codeCalculator = "lambda_handler_calculator.zip"; $handlerCalculator = "lambda_handler_calculator"; echo "First, put the new code into the S3 bucket.\n"; $file = file_get_contents($codeCalculator); $s3client->putObject([ 'Bucket' => $bucketName, 'Key' => $functionName, 'Body' => $file, ]); echo "New code uploaded.\n"; $lambdaService->updateFunctionCode($functionName, $bucketName, $functionName); // Wait for the Lambda code to finish updating. do { $getLambdaFunction = $lambdaService->getFunction($createLambdaFunction['FunctionName']); } while ($getLambdaFunction['Configuration']['LastUpdateStatus'] !== "Successful"); echo "New Lambda code uploaded.\n"; $environment = [ 'Variable' => ['Variables' => ['LOG_LEVEL' => 'DEBUG']], ]; $lambdaService->updateFunctionConfiguration($functionName, $handlerCalculator, $environment); do { $getLambdaFunction = $lambdaService->getFunction($createLambdaFunction['FunctionName']); } while ($getLambdaFunction['Configuration']['LastUpdateStatus'] !== "Successful"); echo "Lambda code updated with new handler and a LOG_LEVEL of DEBUG for more information.\n"; echo "Invoke the new code with some new data.\n"; $calculatorParams = [ 'action' => 'plus', 'x' => 5, 'y' => 4, ]; $invokeFunction = $lambdaService->invoke($functionName, $calculatorParams, "Tail"); $result = json_decode($invokeFunction['Payload']->getContents())->result; echo "Indeed, {$calculatorParams['x']} + {$calculatorParams['y']} does equal $result.\n"; echo "Here's the extra debug info: "; echo base64_decode($invokeFunction['LogResult']) . "\n"; echo "\nBut what happens if you try to divide by zero?\n"; $divZeroParams = [ 'action' => 'divide', 'x' => 5, 'y' => 0, ]; $invokeFunction = $lambdaService->invoke($functionName, $divZeroParams, "Tail"); $result = json_decode($invokeFunction['Payload']->getContents())->result; echo "You get a |$result| result.\n"; echo "And an error message: "; echo base64_decode($invokeFunction['LogResult']) . "\n"; echo "\nHere's all the Lambda functions you have in this Region:\n"; $listLambdaFunctions = $lambdaService->listFunctions(5); $allLambdaFunctions = $listLambdaFunctions['Functions']; $next = $listLambdaFunctions->get('NextMarker'); while ($next != false) { $listLambdaFunctions = $lambdaService->listFunctions(5, $next); $next = $listLambdaFunctions->get('NextMarker'); $allLambdaFunctions = array_merge($allLambdaFunctions, $listLambdaFunctions['Functions']); } foreach ($allLambdaFunctions as $function) { echo "{$function['FunctionName']}\n"; } echo "\n\nAnd don't forget to clean up your data!\n"; $lambdaService->deleteFunction($functionName); echo "Deleted Lambda function.\n"; $iamService->deleteRole($role['RoleName']); echo "Deleted Role.\n"; $deleteObjects = $s3client->listObjectsV2([ 'Bucket' => $bucketName, ]); $deleteObjects = $s3client->deleteObjects([ 'Bucket' => $bucketName, 'Delete' => [ 'Objects' => $deleteObjects['Contents'], ] ]); echo "Deleted all objects from the S3 bucket.\n"; $s3client->deleteBucket(['Bucket' => $bucketName]); echo "Deleted the bucket.\n"; } }

无服务器示例

以下代码示例展示了如何实现一个 Lambda 函数,该函数接收因接收来自 Kinesis 流的记录而触发的事件。该函数检索 Kinesis 有效负载,将 Base64 解码,并记录下记录内容。

适用于 PHP 的 SDK
注意

还有更多相关信息 GitHub。在无服务器示例存储库中查找完整示例,并了解如何进行设置和运行。

通过 PHP 将 Kinesis 事件与 Lambda 结合使用。

// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 <?php # using bref/bref and bref/logger for simplicity use Bref\Context\Context; use Bref\Event\Kinesis\KinesisEvent; use Bref\Event\Kinesis\KinesisHandler; use Bref\Logger\StderrLogger; require __DIR__ . '/vendor/autoload.php'; class Handler extends KinesisHandler { private StderrLogger $logger; public function __construct(StderrLogger $logger) { $this->logger = $logger; } /** * @throws JsonException * @throws \Bref\Event\InvalidLambdaEvent */ public function handleKinesis(KinesisEvent $event, Context $context): void { $this->logger->info("Processing records"); $records = $event->getRecords(); foreach ($records as $record) { $data = $record->getData(); $this->logger->info(json_encode($data)); // TODO: Do interesting work based on the new data // Any exception thrown will be logged and the invocation will be marked as failed } $totalRecords = count($records); $this->logger->info("Successfully processed $totalRecords records"); } } $logger = new StderrLogger(); return new Handler($logger);

以下代码示例演示如何实现 Lambda 函数,该函数接收通过从 DynamoDB 流接收记录而触发的事件。该函数检索 DynamoDB 有效负载,并记录下记录内容。

适用于 PHP 的 SDK
注意

还有更多相关信息 GitHub。在无服务器示例存储库中查找完整示例,并了解如何进行设置和运行。

使用 PHP 将 DynamoDB 事件与 Lambda 结合使用。

// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 <?php # using bref/bref and bref/logger for simplicity use Bref\Context\Context; use Bref\Event\DynamoDb\DynamoDbEvent; use Bref\Event\DynamoDb\DynamoDbHandler; use Bref\Logger\StderrLogger; require __DIR__ . '/vendor/autoload.php'; class Handler extends DynamoDbHandler { private StderrLogger $logger; public function __construct(StderrLogger $logger) { $this->logger = $logger; } /** * @throws JsonException * @throws \Bref\Event\InvalidLambdaEvent */ public function handleDynamoDb(DynamoDbEvent $event, Context $context): void { $this->logger->info("Processing DynamoDb table items"); $records = $event->getRecords(); foreach ($records as $record) { $eventName = $record->getEventName(); $keys = $record->getKeys(); $old = $record->getOldImage(); $new = $record->getNewImage(); $this->logger->info("Event Name:".$eventName."\n"); $this->logger->info("Keys:". json_encode($keys)."\n"); $this->logger->info("Old Image:". json_encode($old)."\n"); $this->logger->info("New Image:". json_encode($new)); // TODO: Do interesting work based on the new data // Any exception thrown will be logged and the invocation will be marked as failed } $totalRecords = count($records); $this->logger->info("Successfully processed $totalRecords items"); } } $logger = new StderrLogger(); return new Handler($logger);

以下代码示例说明如何实现一个 Lambda 函数,该函数接收通过从 DocumentDB 更改流接收记录而触发的事件。该函数检索 DocumentDB 有效负载,并记录下记录内容。

适用于 PHP 的 SDK
注意

还有更多相关信息 GitHub。在无服务器示例存储库中查找完整示例,并了解如何进行设置和运行。

使用 PHP 使用 Lambda 使用亚马逊文档数据库事件。

<?php require __DIR__.'/vendor/autoload.php'; use Bref\Context\Context; use Bref\Event\Handler; class DocumentDBEventHandler implements Handler { public function handle($event, Context $context): string { $events = $event['events'] ?? []; foreach ($events as $record) { $this->logDocumentDBEvent($record['event']); } return 'OK'; } private function logDocumentDBEvent($event): void { // Extract information from the event record $operationType = $event['operationType'] ?? 'Unknown'; $db = $event['ns']['db'] ?? 'Unknown'; $collection = $event['ns']['coll'] ?? 'Unknown'; $fullDocument = $event['fullDocument'] ?? []; // Log the event details echo "Operation type: $operationType\n"; echo "Database: $db\n"; echo "Collection: $collection\n"; echo "Full document: " . json_encode($fullDocument, JSON_PRETTY_PRINT) . "\n"; } } return new DocumentDBEventHandler();

以下代码示例展示了如何实现一个 Lambda 函数,该函数接收通过将对象上传到 S3 桶而触发的事件。该函数从事件参数中检索 S3 存储桶名称和对象密钥,并调用 Amazon S3 API 来检索和记录对象的内容类型。

适用于 PHP 的 SDK
注意

还有更多相关信息 GitHub。在无服务器示例存储库中查找完整示例,并了解如何进行设置和运行。

通过 PHP 将 S3 事件与 Lambda 结合使用。

// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 <?php use Bref\Context\Context; use Bref\Event\S3\S3Event; use Bref\Event\S3\S3Handler; use Bref\Logger\StderrLogger; require __DIR__ . '/vendor/autoload.php'; class Handler extends S3Handler { private StderrLogger $logger; public function __construct(StderrLogger $logger) { $this->logger = $logger; } public function handleS3(S3Event $event, Context $context) : void { $this->logger->info("Processing S3 records"); // Get the object from the event and show its content type $records = $event->getRecords(); foreach ($records as $record) { $bucket = $record->getBucket()->getName(); $key = urldecode($record->getObject()->getKey()); try { $fileSize = urldecode($record->getObject()->getSize()); echo "File Size: " . $fileSize . "\n"; // TODO: Implement your custom processing logic here } catch (Exception $e) { echo $e->getMessage() . "\n"; echo 'Error getting object ' . $key . ' from bucket ' . $bucket . '. Make sure they exist and your bucket is in the same region as this function.' . "\n"; throw $e; } } } } $logger = new StderrLogger(); return new Handler($logger);

以下代码示例展示了如何实现一个 Lambda 函数,该函数接收因接收来自 SNS 主题的消息而触发的事件。该函数从事件参数检索消息并记录每条消息的内容。

适用于 PHP 的 SDK
注意

还有更多相关信息 GitHub。在无服务器示例存储库中查找完整示例,并了解如何进行设置和运行。

通过 PHP 将 SNS 事件与 Lambda 结合使用。

// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 <?php /* Since native PHP support for AWS Lambda is not available, we are utilizing Bref's PHP functions runtime for AWS Lambda. For more information on Bref's PHP runtime for Lambda, refer to: https://bref.sh/docs/runtimes/function Another approach would be to create a custom runtime. A practical example can be found here: https://aws.amazon.com/blogs/apn/aws-lambda-custom-runtime-for-php-a-practical-example/ */ // Additional composer packages may be required when using Bref or any other PHP functions runtime. // require __DIR__ . '/vendor/autoload.php'; use Bref\Context\Context; use Bref\Event\Sns\SnsEvent; use Bref\Event\Sns\SnsHandler; class Handler extends SnsHandler { public function handleSns(SnsEvent $event, Context $context): void { foreach ($event->getRecords() as $record) { $message = $record->getMessage(); // TODO: Implement your custom processing logic here // Any exception thrown will be logged and the invocation will be marked as failed echo "Processed Message: $message" . PHP_EOL; } } } return new Handler();

以下代码示例展示了如何实现一个 Lambda 函数,该函数接收因接收来自 SNS 队列的消息而触发的事件。该函数从事件参数检索消息并记录每条消息的内容。

适用于 PHP 的 SDK
注意

还有更多相关信息 GitHub。在无服务器示例存储库中查找完整示例,并了解如何进行设置和运行。

使用 PHP 将 SQS 事件与 Lambda 结合使用。

// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 <?php # using bref/bref and bref/logger for simplicity use Bref\Context\Context; use Bref\Event\InvalidLambdaEvent; use Bref\Event\Sqs\SqsEvent; use Bref\Event\Sqs\SqsHandler; use Bref\Logger\StderrLogger; require __DIR__ . '/vendor/autoload.php'; class Handler extends SqsHandler { private StderrLogger $logger; public function __construct(StderrLogger $logger) { $this->logger = $logger; } /** * @throws InvalidLambdaEvent */ public function handleSqs(SqsEvent $event, Context $context): void { foreach ($event->getRecords() as $record) { $body = $record->getBody(); // TODO: Do interesting work based on the new message } } } $logger = new StderrLogger(); return new Handler($logger);

以下代码示例展示了如何为接收来自 Kinesis 流的事件的 Lambda 函数实现部分批处理响应。该函数在响应中报告批处理项目失败,并指示 Lambda 稍后重试这些消息。

适用于 PHP 的 SDK
注意

还有更多相关信息 GitHub。在无服务器示例存储库中查找完整示例,并了解如何进行设置和运行。

报告通过 PHP 进行 Lambda Kinesis 批处理项目失败。

// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 <?php # using bref/bref and bref/logger for simplicity use Bref\Context\Context; use Bref\Event\Kinesis\KinesisEvent; use Bref\Event\Handler as StdHandler; use Bref\Logger\StderrLogger; require __DIR__ . '/vendor/autoload.php'; class Handler implements StdHandler { private StderrLogger $logger; public function __construct(StderrLogger $logger) { $this->logger = $logger; } /** * @throws JsonException * @throws \Bref\Event\InvalidLambdaEvent */ public function handle(mixed $event, Context $context): array { $kinesisEvent = new KinesisEvent($event); $this->logger->info("Processing records"); $records = $kinesisEvent->getRecords(); $failedRecords = []; foreach ($records as $record) { try { $data = $record->getData(); $this->logger->info(json_encode($data)); // TODO: Do interesting work based on the new data } catch (Exception $e) { $this->logger->error($e->getMessage()); // failed processing the record $failedRecords[] = $record->getSequenceNumber(); } } $totalRecords = count($records); $this->logger->info("Successfully processed $totalRecords records"); // change format for the response $failures = array_map( fn(string $sequenceNumber) => ['itemIdentifier' => $sequenceNumber], $failedRecords ); return [ 'batchItemFailures' => $failures ]; } } $logger = new StderrLogger(); return new Handler($logger);

以下代码示例演示如何为接收来自 DynamoDB 流的事件的 Lambda 函数实现部分批量响应。该函数在响应中报告批处理项目失败,并指示 Lambda 稍后重试这些消息。

适用于 PHP 的 SDK
注意

还有更多相关信息 GitHub。在无服务器示例存储库中查找完整示例,并了解如何进行设置和运行。

报告使用 PHP 通过 Lambda 进行 DynamoDB 批处理项目失败。

# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 <?php # using bref/bref and bref/logger for simplicity use Bref\Context\Context; use Bref\Event\DynamoDb\DynamoDbEvent; use Bref\Event\Handler as StdHandler; use Bref\Logger\StderrLogger; require __DIR__ . '/vendor/autoload.php'; class Handler implements StdHandler { private StderrLogger $logger; public function __construct(StderrLogger $logger) { $this->logger = $logger; } /** * @throws JsonException * @throws \Bref\Event\InvalidLambdaEvent */ public function handle(mixed $event, Context $context): array { $dynamoDbEvent = new DynamoDbEvent($event); $this->logger->info("Processing records"); $records = $dynamoDbEvent->getRecords(); $failedRecords = []; foreach ($records as $record) { try { $data = $record->getData(); $this->logger->info(json_encode($data)); // TODO: Do interesting work based on the new data } catch (Exception $e) { $this->logger->error($e->getMessage()); // failed processing the record $failedRecords[] = $record->getSequenceNumber(); } } $totalRecords = count($records); $this->logger->info("Successfully processed $totalRecords records"); // change format for the response $failures = array_map( fn(string $sequenceNumber) => ['itemIdentifier' => $sequenceNumber], $failedRecords ); return [ 'batchItemFailures' => $failures ]; } } $logger = new StderrLogger(); return new Handler($logger);

以下代码示例展示了如何为接收来自 SQS 队列的事件的 Lambda 函数实现部分批处理响应。该函数在响应中报告批处理项目失败,并指示 Lambda 稍后重试这些消息。

适用于 PHP 的 SDK
注意

还有更多相关信息 GitHub。在无服务器示例存储库中查找完整示例,并了解如何进行设置和运行。

报告使用 PHP 进行 Lambda SQS 批处理项目失败。

// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 <?php use Bref\Context\Context; use Bref\Event\Sqs\SqsEvent; use Bref\Event\Sqs\SqsHandler; use Bref\Logger\StderrLogger; require __DIR__ . '/vendor/autoload.php'; class Handler extends SqsHandler { private StderrLogger $logger; public function __construct(StderrLogger $logger) { $this->logger = $logger; } /** * @throws JsonException * @throws \Bref\Event\InvalidLambdaEvent */ public function handleSqs(SqsEvent $event, Context $context): void { $this->logger->info("Processing SQS records"); $records = $event->getRecords(); foreach ($records as $record) { try { // Assuming the SQS message is in JSON format $message = json_decode($record->getBody(), true); $this->logger->info(json_encode($message)); // TODO: Implement your custom processing logic here } catch (Exception $e) { $this->logger->error($e->getMessage()); // failed processing the record $this->markAsFailed($record); } } $totalRecords = count($records); $this->logger->info("Successfully processed $totalRecords SQS records"); } } $logger = new StderrLogger(); return new Handler($logger);