使用 PHP 開發套件的 Lambda 範例 - AWS SDK for PHP

本文為英文版的機器翻譯版本,如內容有任何歧義或不一致之處,概以英文版為準。

使用 PHP 開發套件的 Lambda 範例

下列程式碼範例說明如何使用 Lambda 來執行動作和實作常見案例。 AWS SDK for PHP

Actions 是大型程式的程式碼摘錄,必須在內容中執行。雖然動作會告訴您如何呼叫個別服務函數,但您可以在其相關情境和跨服務範例中查看內容中的動作。

Scenarios (案例) 是向您展示如何呼叫相同服務中的多個函數來完成特定任務的程式碼範例。

每個範例都包含一個連結 GitHub,您可以在其中找到如何在內容中設定和執行程式碼的指示。

動作

下列程式碼範例會示範如何使用CreateFunction

適用於 PHP 的開發套件
注意

還有更多關於 GitHub。尋找完整範例,並了解如何在AWS 設定和執行程式碼範例儲存庫

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 詳細資訊,請參閱 AWS SDK for PHP API 參考CreateFunction中的。

下列程式碼範例會示範如何使用DeleteFunction

適用於 PHP 的開發套件
注意

還有更多關於 GitHub。尋找完整範例,並了解如何在AWS 設定和執行程式碼範例儲存庫

public function deleteFunction($functionName) { return $this->lambdaClient->deleteFunction([ 'FunctionName' => $functionName, ]); }
  • 如需 API 詳細資訊,請參閱 AWS SDK for PHP API 參考DeleteFunction中的。

下列程式碼範例會示範如何使用GetFunction

適用於 PHP 的開發套件
注意

還有更多關於 GitHub。尋找完整範例,並了解如何在AWS 設定和執行程式碼範例儲存庫

public function getFunction($functionName) { return $this->lambdaClient->getFunction([ 'FunctionName' => $functionName, ]); }
  • 如需 API 詳細資訊,請參閱 AWS SDK for PHP API 參考GetFunction中的。

下列程式碼範例會示範如何使用Invoke

適用於 PHP 的開發套件
注意

還有更多關於 GitHub。尋找完整範例,並了解如何在AWS 設定和執行程式碼範例儲存庫

public function invoke($functionName, $params, $logType = 'None') { return $this->lambdaClient->invoke([ 'FunctionName' => $functionName, 'Payload' => json_encode($params), 'LogType' => $logType, ]); }
  • 如需 API 的詳細資訊,請參閱《AWS SDK for PHP API 參考》中的「Invoke」。

下列程式碼範例會示範如何使用ListFunctions

適用於 PHP 的開發套件
注意

還有更多關於 GitHub。尋找完整範例,並了解如何在AWS 設定和執行程式碼範例儲存庫

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 詳細資訊,請參閱 AWS SDK for PHP API 參考ListFunctions中的。

下列程式碼範例會示範如何使用UpdateFunctionCode

適用於 PHP 的開發套件
注意

還有更多關於 GitHub。尋找完整範例,並了解如何在AWS 設定和執行程式碼範例儲存庫

public function updateFunctionCode($functionName, $s3Bucket, $s3Key) { return $this->lambdaClient->updateFunctionCode([ 'FunctionName' => $functionName, 'S3Bucket' => $s3Bucket, 'S3Key' => $s3Key, ]); }
  • 如需 API 詳細資訊,請參閱 AWS SDK for PHP API 參考UpdateFunctionCode中的。

下列程式碼範例會示範如何使用UpdateFunctionConfiguration

適用於 PHP 的開發套件
注意

還有更多關於 GitHub。尋找完整範例,並了解如何在AWS 設定和執行程式碼範例儲存庫

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

案例

以下程式碼範例顯示做法:

  • 建立 IAM 角色和 Lambda 函數,然後上傳處理常式程式碼。

  • 調用具有單一參數的函數並取得結果。

  • 更新函數程式碼並使用環境變數進行設定。

  • 調用具有新參數的函數並取得結果。顯示傳回的執行日誌。

  • 列出您帳戶的函數,然後清理相關資源。

如需詳細資訊,請參閱使用主控台建立 Lambda 函數

適用於 PHP 的開發套件
注意

還有更多關於 GitHub。尋找完整範例,並了解如何在AWS 設定和執行程式碼範例儲存庫

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 的開發套件
注意

還有更多關於 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\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 函數,該函數會接收透過將物件上傳至 S3 儲存貯體而觸發的事件。此函數會從事件參數擷取 S3 儲存貯體名稱和物件金鑰,並呼叫 Amazon S3 API 以擷取和記錄物件的內容類型。

適用於 PHP 的開發套件
注意

還有更多關於 GitHub。尋找完整範例,並了解如何在無伺服器範例儲存庫中設定和執行。

使用 PHP 使用 Lambda 使用 S3 事件。

// 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 的開發套件
注意

還有更多關於 GitHub。尋找完整範例,並了解如何在無伺服器範例儲存庫中設定和執行。

使用 PHP 搭配 Lambda 來使用 SNS 事件。

// 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 函數,該函數會接收由 SQS 佇列接收訊息而觸發的事件。函數會從事件參數擷取訊息,並記錄每一則訊息的內容。

適用於 PHP 的開發套件
注意

還有更多關於 GitHub。尋找完整範例,並了解如何在無伺服器範例儲存庫中設定和執行。

使用 PHP 與 Lambda 一起使用 SQS 事件。

// 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 的開發套件
注意

還有更多關於 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);

下列程式碼範例示範如何針對接收來自 SQS 佇列之事件的 Lambda 函數實作部分批次回應。此函數會在回應中報告批次項目失敗,指示 Lambda 稍後重試這些訊息。

適用於 PHP 的開發套件
注意

還有更多關於 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);