를 사용하는 DynamoDB 예제 SDK PHP - AWS SDK코드 예제

AWS 문서 AWS SDK SDK 예제 GitHub 리포지토리에 더 많은 예제가 있습니다.

기계 번역으로 제공되는 번역입니다. 제공된 번역과 원본 영어의 내용이 상충하는 경우에는 영어 버전이 우선합니다.

를 사용하는 DynamoDB 예제 SDK PHP

다음 코드 예제는 DynamoDB와 AWS SDK for PHP 함께 사용하여 작업을 수행하고 일반적인 시나리오를 구현하는 방법을 보여줍니다.

기본 사항은 서비스 내에서 필수 작업을 수행하는 방법을 보여주는 코드 예제입니다.

작업은 대규모 프로그램에서 발췌한 코드이며 컨텍스트에 맞춰 실행해야 합니다. 작업은 개별 서비스 함수를 직접적으로 호출하는 방법을 보여주며 관련 시나리오의 컨텍스트에 맞는 작업을 볼 수 있습니다.

시나리오는 동일한 서비스 내에서 또는 다른 AWS 서비스와 결합된 상태에서 여러 함수를 호출하여 특정 태스크를 수행하는 방법을 보여주는 코드 예제입니다.

각 예제에는 전체 소스 코드에 대한 링크가 포함되어 있으며, 여기에서 상황에 맞게 코드를 설정하고 실행하는 방법에 대한 지침을 찾을 수 있습니다.

기본 사항

다음 코드 예시는 다음과 같은 작업을 수행하는 방법을 보여줍니다.

  • 영화 데이터를 저장할 수 있는 테이블을 생성합니다.

  • 테이블에 하나의 영화를 추가하고 가져오고 업데이트합니다.

  • 샘플 JSON 파일에서 테이블에 동영상 데이터를 씁니다.

  • 특정 연도에 개봉된 영화를 쿼리합니다.

  • 특정 연도 범위 동안 개봉된 영화를 스캔합니다.

  • 테이블에서 영화를 삭제한 다음, 테이블을 삭제합니다.

PHP용 SDK
참고

더 많은 정보가 있습니다 GitHub. AWS 코드 예시 리포지토리에서 전체 예시를 찾고 설정 및 실행하는 방법을 배워보세요.

namespace DynamoDb\Basics; use Aws\DynamoDb\Marshaler; use DynamoDb; use DynamoDb\DynamoDBAttribute; use DynamoDb\DynamoDBService; use function AwsUtilities\loadMovieData; use function AwsUtilities\testable_readline; class GettingStartedWithDynamoDB { public function run() { echo("\n"); echo("--------------------------------------\n"); print("Welcome to the Amazon DynamoDB getting started demo using PHP!\n"); echo("--------------------------------------\n"); $uuid = uniqid(); $service = new DynamoDBService(); $tableName = "ddb_demo_table_$uuid"; $service->createTable( $tableName, [ new DynamoDBAttribute('year', 'N', 'HASH'), new DynamoDBAttribute('title', 'S', 'RANGE') ] ); echo "Waiting for table..."; $service->dynamoDbClient->waitUntil("TableExists", ['TableName' => $tableName]); echo "table $tableName found!\n"; echo "What's the name of the last movie you watched?\n"; while (empty($movieName)) { $movieName = testable_readline("Movie name: "); } echo "And what year was it released?\n"; $movieYear = "year"; while (!is_numeric($movieYear) || intval($movieYear) != $movieYear) { $movieYear = testable_readline("Year released: "); } $service->putItem([ 'Item' => [ 'year' => [ 'N' => "$movieYear", ], 'title' => [ 'S' => $movieName, ], ], 'TableName' => $tableName, ]); echo "How would you rate the movie from 1-10?\n"; $rating = 0; while (!is_numeric($rating) || intval($rating) != $rating || $rating < 1 || $rating > 10) { $rating = testable_readline("Rating (1-10): "); } echo "What was the movie about?\n"; while (empty($plot)) { $plot = testable_readline("Plot summary: "); } $key = [ 'Item' => [ 'title' => [ 'S' => $movieName, ], 'year' => [ 'N' => $movieYear, ], ] ]; $attributes = ["rating" => [ 'AttributeName' => 'rating', 'AttributeType' => 'N', 'Value' => $rating, ], 'plot' => [ 'AttributeName' => 'plot', 'AttributeType' => 'S', 'Value' => $plot, ] ]; $service->updateItemAttributesByKey($tableName, $key, $attributes); echo "Movie added and updated."; $batch = json_decode(loadMovieData()); $service->writeBatch($tableName, $batch); $movie = $service->getItemByKey($tableName, $key); echo "\nThe movie {$movie['Item']['title']['S']} was released in {$movie['Item']['year']['N']}.\n"; echo "What rating would you like to give {$movie['Item']['title']['S']}?\n"; $rating = 0; while (!is_numeric($rating) || intval($rating) != $rating || $rating < 1 || $rating > 10) { $rating = testable_readline("Rating (1-10): "); } $service->updateItemAttributeByKey($tableName, $key, 'rating', 'N', $rating); $movie = $service->getItemByKey($tableName, $key); echo "Ok, you have rated {$movie['Item']['title']['S']} as a {$movie['Item']['rating']['N']}\n"; $service->deleteItemByKey($tableName, $key); echo "But, bad news, this was a trap. That movie has now been deleted because of your rating...harsh.\n"; echo "That's okay though. The book was better. Now, for something lighter, in what year were you born?\n"; $birthYear = "not a number"; while (!is_numeric($birthYear) || $birthYear >= date("Y")) { $birthYear = testable_readline("Birth year: "); } $birthKey = [ 'Key' => [ 'year' => [ 'N' => "$birthYear", ], ], ]; $result = $service->query($tableName, $birthKey); $marshal = new Marshaler(); echo "Here are the movies in our collection released the year you were born:\n"; $oops = "Oops! There were no movies released in that year (that we know of).\n"; $display = ""; foreach ($result['Items'] as $movie) { $movie = $marshal->unmarshalItem($movie); $display .= $movie['title'] . "\n"; } echo ($display) ?: $oops; $yearsKey = [ 'Key' => [ 'year' => [ 'N' => [ 'minRange' => 1990, 'maxRange' => 1999, ], ], ], ]; $filter = "year between 1990 and 1999"; echo "\nHere's a list of all the movies released in the 90s:\n"; $result = $service->scan($tableName, $yearsKey, $filter); foreach ($result['Items'] as $movie) { $movie = $marshal->unmarshalItem($movie); echo $movie['title'] . "\n"; } echo "\nCleaning up this demo by deleting table $tableName...\n"; $service->deleteTable($tableName); } }

작업

다음 코드 예시에서는 BatchExecuteStatement을 사용하는 방법을 보여 줍니다.

PHP용 SDK
참고

자세한 내용은 다음과 같습니다 GitHub. AWS 코드 예시 리포지토리에서 전체 예시를 찾고 설정 및 실행하는 방법을 배워보세요.

public function getItemByPartiQLBatch(string $tableName, array $keys): Result { $statements = []; foreach ($keys as $key) { list($statement, $parameters) = $this->buildStatementAndParameters("SELECT", $tableName, $key['Item']); $statements[] = [ 'Statement' => "$statement", 'Parameters' => $parameters, ]; } return $this->dynamoDbClient->batchExecuteStatement([ 'Statements' => $statements, ]); } public function insertItemByPartiQLBatch(string $statement, array $parameters) { $this->dynamoDbClient->batchExecuteStatement([ 'Statements' => [ [ 'Statement' => "$statement", 'Parameters' => $parameters, ], ], ]); } public function updateItemByPartiQLBatch(string $statement, array $parameters) { $this->dynamoDbClient->batchExecuteStatement([ 'Statements' => [ [ 'Statement' => "$statement", 'Parameters' => $parameters, ], ], ]); } public function deleteItemByPartiQLBatch(string $statement, array $parameters) { $this->dynamoDbClient->batchExecuteStatement([ 'Statements' => [ [ 'Statement' => "$statement", 'Parameters' => $parameters, ], ], ]); }

다음 코드 예시에서는 BatchWriteItem을 사용하는 방법을 보여 줍니다.

PHP용 SDK
참고

더 많은 정보가 있습니다 GitHub. AWS 코드 예시 리포지토리에서 전체 예시를 찾고 설정 및 실행하는 방법을 배워보세요.

public function writeBatch(string $TableName, array $Batch, int $depth = 2) { if (--$depth <= 0) { throw new Exception("Max depth exceeded. Please try with fewer batch items or increase depth."); } $marshal = new Marshaler(); $total = 0; foreach (array_chunk($Batch, 25) as $Items) { foreach ($Items as $Item) { $BatchWrite['RequestItems'][$TableName][] = ['PutRequest' => ['Item' => $marshal->marshalItem($Item)]]; } try { echo "Batching another " . count($Items) . " for a total of " . ($total += count($Items)) . " items!\n"; $response = $this->dynamoDbClient->batchWriteItem($BatchWrite); $BatchWrite = []; } catch (Exception $e) { echo "uh oh..."; echo $e->getMessage(); die(); } if ($total >= 250) { echo "250 movies is probably enough. Right? We can stop there.\n"; break; } } }

다음 코드 예시에서는 CreateTable을 사용하는 방법을 보여 줍니다.

PHP용 SDK
참고

더 많은 정보가 있습니다 GitHub. AWS 코드 예시 리포지토리에서 전체 예시를 찾고 설정 및 실행하는 방법을 배워보세요.

테이블을 생성합니다.

$tableName = "ddb_demo_table_$uuid"; $service->createTable( $tableName, [ new DynamoDBAttribute('year', 'N', 'HASH'), new DynamoDBAttribute('title', 'S', 'RANGE') ] ); public function createTable(string $tableName, array $attributes) { $keySchema = []; $attributeDefinitions = []; foreach ($attributes as $attribute) { if (is_a($attribute, DynamoDBAttribute::class)) { $keySchema[] = ['AttributeName' => $attribute->AttributeName, 'KeyType' => $attribute->KeyType]; $attributeDefinitions[] = ['AttributeName' => $attribute->AttributeName, 'AttributeType' => $attribute->AttributeType]; } } $this->dynamoDbClient->createTable([ 'TableName' => $tableName, 'KeySchema' => $keySchema, 'AttributeDefinitions' => $attributeDefinitions, 'ProvisionedThroughput' => ['ReadCapacityUnits' => 10, 'WriteCapacityUnits' => 10], ]); }

다음 코드 예시에서는 DeleteItem을 사용하는 방법을 보여 줍니다.

PHP용 SDK
참고

더 많은 정보가 있습니다 GitHub. AWS 코드 예시 리포지토리에서 전체 예시를 찾고 설정 및 실행하는 방법을 배워보세요.

$key = [ 'Item' => [ 'title' => [ 'S' => $movieName, ], 'year' => [ 'N' => $movieYear, ], ] ]; $service->deleteItemByKey($tableName, $key); echo "But, bad news, this was a trap. That movie has now been deleted because of your rating...harsh.\n"; public function deleteItemByKey(string $tableName, array $key) { $this->dynamoDbClient->deleteItem([ 'Key' => $key['Item'], 'TableName' => $tableName, ]); }

다음 코드 예시에서는 DeleteTable을 사용하는 방법을 보여 줍니다.

PHP용 SDK
참고

더 많은 정보가 있습니다 GitHub. AWS 코드 예시 리포지토리에서 전체 예시를 찾고 설정 및 실행하는 방법을 배워보세요.

public function deleteTable(string $TableName) { $this->customWaiter(function () use ($TableName) { return $this->dynamoDbClient->deleteTable([ 'TableName' => $TableName, ]); }); }

다음 코드 예시에서는 ExecuteStatement을 사용하는 방법을 보여 줍니다.

PHP용 SDK
참고

더 많은 정보가 있습니다 GitHub. AWS 코드 예시 리포지토리에서 전체 예시를 찾고 설정 및 실행하는 방법을 배워보세요.

public function insertItemByPartiQL(string $statement, array $parameters) { $this->dynamoDbClient->executeStatement([ 'Statement' => "$statement", 'Parameters' => $parameters, ]); } public function getItemByPartiQL(string $tableName, array $key): Result { list($statement, $parameters) = $this->buildStatementAndParameters("SELECT", $tableName, $key['Item']); return $this->dynamoDbClient->executeStatement([ 'Parameters' => $parameters, 'Statement' => $statement, ]); } public function updateItemByPartiQL(string $statement, array $parameters) { $this->dynamoDbClient->executeStatement([ 'Statement' => $statement, 'Parameters' => $parameters, ]); } public function deleteItemByPartiQL(string $statement, array $parameters) { $this->dynamoDbClient->executeStatement([ 'Statement' => $statement, 'Parameters' => $parameters, ]); }

다음 코드 예시에서는 GetItem을 사용하는 방법을 보여 줍니다.

PHP용 SDK
참고

더 많은 정보가 있습니다 GitHub. AWS 코드 예시 리포지토리에서 전체 예시를 찾고 설정 및 실행하는 방법을 배워보세요.

$movie = $service->getItemByKey($tableName, $key); echo "\nThe movie {$movie['Item']['title']['S']} was released in {$movie['Item']['year']['N']}.\n"; public function getItemByKey(string $tableName, array $key) { return $this->dynamoDbClient->getItem([ 'Key' => $key['Item'], 'TableName' => $tableName, ]); }

다음 코드 예시에서는 ListTables을 사용하는 방법을 보여 줍니다.

PHP용 SDK
참고

더 많은 정보가 있습니다 GitHub. AWS 코드 예시 리포지토리에서 전체 예시를 찾고 설정 및 실행하는 방법을 배워보세요.

public function listTables($exclusiveStartTableName = "", $limit = 100) { $this->dynamoDbClient->listTables([ 'ExclusiveStartTableName' => $exclusiveStartTableName, 'Limit' => $limit, ]); }

다음 코드 예시에서는 PutItem을 사용하는 방법을 보여 줍니다.

PHP용 SDK
참고

더 많은 정보가 있습니다 GitHub. AWS 코드 예시 리포지토리에서 전체 예시를 찾고 설정 및 실행하는 방법을 배워보세요.

echo "What's the name of the last movie you watched?\n"; while (empty($movieName)) { $movieName = testable_readline("Movie name: "); } echo "And what year was it released?\n"; $movieYear = "year"; while (!is_numeric($movieYear) || intval($movieYear) != $movieYear) { $movieYear = testable_readline("Year released: "); } $service->putItem([ 'Item' => [ 'year' => [ 'N' => "$movieYear", ], 'title' => [ 'S' => $movieName, ], ], 'TableName' => $tableName, ]); public function putItem(array $array) { $this->dynamoDbClient->putItem($array); }

다음 코드 예시에서는 Query을 사용하는 방법을 보여 줍니다.

PHP용 SDK
참고

더 많은 정보가 있습니다 GitHub. AWS 코드 예시 리포지토리에서 전체 예시를 찾고 설정 및 실행하는 방법을 배워보세요.

$birthKey = [ 'Key' => [ 'year' => [ 'N' => "$birthYear", ], ], ]; $result = $service->query($tableName, $birthKey); public function query(string $tableName, $key) { $expressionAttributeValues = []; $expressionAttributeNames = []; $keyConditionExpression = ""; $index = 1; foreach ($key as $name => $value) { $keyConditionExpression .= "#" . array_key_first($value) . " = :v$index,"; $expressionAttributeNames["#" . array_key_first($value)] = array_key_first($value); $hold = array_pop($value); $expressionAttributeValues[":v$index"] = [ array_key_first($hold) => array_pop($hold), ]; } $keyConditionExpression = substr($keyConditionExpression, 0, -1); $query = [ 'ExpressionAttributeValues' => $expressionAttributeValues, 'ExpressionAttributeNames' => $expressionAttributeNames, 'KeyConditionExpression' => $keyConditionExpression, 'TableName' => $tableName, ]; return $this->dynamoDbClient->query($query); }
  • 자세한 API 내용은 AWS SDK for PHP API참조 쿼리를 참조하십시오.

다음 코드 예시에서는 Scan을 사용하는 방법을 보여 줍니다.

PHP용 SDK
참고

자세한 내용은 다음과 같습니다 GitHub. AWS 코드 예시 리포지토리에서 전체 예시를 찾고 설정 및 실행하는 방법을 배워보세요.

$yearsKey = [ 'Key' => [ 'year' => [ 'N' => [ 'minRange' => 1990, 'maxRange' => 1999, ], ], ], ]; $filter = "year between 1990 and 1999"; echo "\nHere's a list of all the movies released in the 90s:\n"; $result = $service->scan($tableName, $yearsKey, $filter); foreach ($result['Items'] as $movie) { $movie = $marshal->unmarshalItem($movie); echo $movie['title'] . "\n"; } public function scan(string $tableName, array $key, string $filters) { $query = [ 'ExpressionAttributeNames' => ['#year' => 'year'], 'ExpressionAttributeValues' => [ ":min" => ['N' => '1990'], ":max" => ['N' => '1999'], ], 'FilterExpression' => "#year between :min and :max", 'TableName' => $tableName, ]; return $this->dynamoDbClient->scan($query); }
  • 자세한 API 내용은 AWS SDK for PHP API참조 스캔을 참조하십시오.

다음 코드 예시에서는 UpdateItem을 사용하는 방법을 보여 줍니다.

PHP용 SDK
참고

자세한 내용은 다음과 같습니다 GitHub. AWS 코드 예시 리포지토리에서 전체 예시를 찾고 설정 및 실행하는 방법을 배워보세요.

echo "What rating would you like to give {$movie['Item']['title']['S']}?\n"; $rating = 0; while (!is_numeric($rating) || intval($rating) != $rating || $rating < 1 || $rating > 10) { $rating = testable_readline("Rating (1-10): "); } $service->updateItemAttributeByKey($tableName, $key, 'rating', 'N', $rating); public function updateItemAttributeByKey( string $tableName, array $key, string $attributeName, string $attributeType, string $newValue ) { $this->dynamoDbClient->updateItem([ 'Key' => $key['Item'], 'TableName' => $tableName, 'UpdateExpression' => "set #NV=:NV", 'ExpressionAttributeNames' => [ '#NV' => $attributeName, ], 'ExpressionAttributeValues' => [ ':NV' => [ $attributeType => $newValue ] ], ]); }

시나리오

다음 코드 예시에서는 사용자가 레이블을 사용하여 사진을 관리할 수 있는 서버리스 애플리케이션을 생성하는 방법을 보여줍니다.

PHP용 SDK

Amazon Rekognition을 사용하여 이미지에서 레이블을 감지하고 나중에 검색할 수 있도록 저장하는 사진 자산 관리 애플리케이션을 개발하는 방법을 보여줍니다.

전체 소스 코드와 설정 및 실행 방법에 대한 지침은 의 전체 예제를 참조하십시오 GitHub.

이 예제의 출처에 대한 자세한 내용은 AWS  커뮤니티의 게시물을 참조하십시오.

이 예시에서 사용되는 서비스
  • API게이트웨이

  • DynamoDB

  • Lambda

  • Amazon Rekognition

  • Amazon S3

  • 아마존 SNS

다음 코드 예시는 다음과 같은 작업을 수행하는 방법을 보여줍니다.

  • 여러 SELECT 명령문을 실행하여 항목을 일괄 처리하십시오.

  • INSERT명령문을 여러 개 실행하여 항목 배치를 추가합니다.

  • 여러 UPDATE 명령문을 실행하여 항목 배치를 업데이트합니다.

  • DELETE명령문을 여러 개 실행하여 항목 배치를 삭제합니다.

PHP용 SDK
참고

자세한 내용은 다음과 같습니다 GitHub. AWS 코드 예시 리포지토리에서 전체 예시를 찾고 설정 및 실행하는 방법을 배워보세요.

namespace DynamoDb\PartiQL_Basics; use Aws\DynamoDb\Marshaler; use DynamoDb; use DynamoDb\DynamoDBAttribute; use function AwsUtilities\loadMovieData; use function AwsUtilities\testable_readline; class GettingStartedWithPartiQLBatch { public function run() { echo("\n"); echo("--------------------------------------\n"); print("Welcome to the Amazon DynamoDB - PartiQL getting started demo using PHP!\n"); echo("--------------------------------------\n"); $uuid = uniqid(); $service = new DynamoDb\DynamoDBService(); $tableName = "partiql_demo_table_$uuid"; $service->createTable( $tableName, [ new DynamoDBAttribute('year', 'N', 'HASH'), new DynamoDBAttribute('title', 'S', 'RANGE') ] ); echo "Waiting for table..."; $service->dynamoDbClient->waitUntil("TableExists", ['TableName' => $tableName]); echo "table $tableName found!\n"; echo "What's the name of the last movie you watched?\n"; while (empty($movieName)) { $movieName = testable_readline("Movie name: "); } echo "And what year was it released?\n"; $movieYear = "year"; while (!is_numeric($movieYear) || intval($movieYear) != $movieYear) { $movieYear = testable_readline("Year released: "); } $key = [ 'Item' => [ 'year' => [ 'N' => "$movieYear", ], 'title' => [ 'S' => $movieName, ], ], ]; list($statement, $parameters) = $service->buildStatementAndParameters("INSERT", $tableName, $key); $service->insertItemByPartiQLBatch($statement, $parameters); echo "How would you rate the movie from 1-10?\n"; $rating = 0; while (!is_numeric($rating) || intval($rating) != $rating || $rating < 1 || $rating > 10) { $rating = testable_readline("Rating (1-10): "); } echo "What was the movie about?\n"; while (empty($plot)) { $plot = testable_readline("Plot summary: "); } $attributes = [ new DynamoDBAttribute('rating', 'N', 'HASH', $rating), new DynamoDBAttribute('plot', 'S', 'RANGE', $plot), ]; list($statement, $parameters) = $service->buildStatementAndParameters("UPDATE", $tableName, $key, $attributes); $service->updateItemByPartiQLBatch($statement, $parameters); echo "Movie added and updated.\n"; $batch = json_decode(loadMovieData()); $service->writeBatch($tableName, $batch); $movie = $service->getItemByPartiQLBatch($tableName, [$key]); echo "\nThe movie {$movie['Responses'][0]['Item']['title']['S']} was released in {$movie['Responses'][0]['Item']['year']['N']}.\n"; echo "What rating would you like to give {$movie['Responses'][0]['Item']['title']['S']}?\n"; $rating = 0; while (!is_numeric($rating) || intval($rating) != $rating || $rating < 1 || $rating > 10) { $rating = testable_readline("Rating (1-10): "); } $attributes = [ new DynamoDBAttribute('rating', 'N', 'HASH', $rating), new DynamoDBAttribute('plot', 'S', 'RANGE', $plot) ]; list($statement, $parameters) = $service->buildStatementAndParameters("UPDATE", $tableName, $key, $attributes); $service->updateItemByPartiQLBatch($statement, $parameters); $movie = $service->getItemByPartiQLBatch($tableName, [$key]); echo "Okay, you have rated {$movie['Responses'][0]['Item']['title']['S']} as a {$movie['Responses'][0]['Item']['rating']['N']}\n"; $service->deleteItemByPartiQLBatch($statement, $parameters); echo "But, bad news, this was a trap. That movie has now been deleted because of your rating...harsh.\n"; echo "That's okay though. The book was better. Now, for something lighter, in what year were you born?\n"; $birthYear = "not a number"; while (!is_numeric($birthYear) || $birthYear >= date("Y")) { $birthYear = testable_readline("Birth year: "); } $birthKey = [ 'Key' => [ 'year' => [ 'N' => "$birthYear", ], ], ]; $result = $service->query($tableName, $birthKey); $marshal = new Marshaler(); echo "Here are the movies in our collection released the year you were born:\n"; $oops = "Oops! There were no movies released in that year (that we know of).\n"; $display = ""; foreach ($result['Items'] as $movie) { $movie = $marshal->unmarshalItem($movie); $display .= $movie['title'] . "\n"; } echo ($display) ?: $oops; $yearsKey = [ 'Key' => [ 'year' => [ 'N' => [ 'minRange' => 1990, 'maxRange' => 1999, ], ], ], ]; $filter = "year between 1990 and 1999"; echo "\nHere's a list of all the movies released in the 90s:\n"; $result = $service->scan($tableName, $yearsKey, $filter); foreach ($result['Items'] as $movie) { $movie = $marshal->unmarshalItem($movie); echo $movie['title'] . "\n"; } echo "\nCleaning up this demo by deleting table $tableName...\n"; $service->deleteTable($tableName); } } public function insertItemByPartiQLBatch(string $statement, array $parameters) { $this->dynamoDbClient->batchExecuteStatement([ 'Statements' => [ [ 'Statement' => "$statement", 'Parameters' => $parameters, ], ], ]); } public function getItemByPartiQLBatch(string $tableName, array $keys): Result { $statements = []; foreach ($keys as $key) { list($statement, $parameters) = $this->buildStatementAndParameters("SELECT", $tableName, $key['Item']); $statements[] = [ 'Statement' => "$statement", 'Parameters' => $parameters, ]; } return $this->dynamoDbClient->batchExecuteStatement([ 'Statements' => $statements, ]); } public function updateItemByPartiQLBatch(string $statement, array $parameters) { $this->dynamoDbClient->batchExecuteStatement([ 'Statements' => [ [ 'Statement' => "$statement", 'Parameters' => $parameters, ], ], ]); } public function deleteItemByPartiQLBatch(string $statement, array $parameters) { $this->dynamoDbClient->batchExecuteStatement([ 'Statements' => [ [ 'Statement' => "$statement", 'Parameters' => $parameters, ], ], ]); }

다음 코드 예시는 다음과 같은 작업을 수행하는 방법을 보여줍니다.

  • SELECT명령문을 실행하여 항목을 가져옵니다.

  • INSERT명령문을 실행하여 항목을 추가합니다.

  • UPDATE명령문을 실행하여 항목을 업데이트합니다.

  • DELETE명령문을 실행하여 항목을 삭제합니다.

PHP용 SDK
참고

자세한 내용은 다음과 같습니다 GitHub. AWS 코드 예시 리포지토리에서 전체 예시를 찾고 설정 및 실행하는 방법을 배워보세요.

namespace DynamoDb\PartiQL_Basics; use Aws\DynamoDb\Marshaler; use DynamoDb; use DynamoDb\DynamoDBAttribute; use function AwsUtilities\testable_readline; use function AwsUtilities\loadMovieData; class GettingStartedWithPartiQL { public function run() { echo("\n"); echo("--------------------------------------\n"); print("Welcome to the Amazon DynamoDB - PartiQL getting started demo using PHP!\n"); echo("--------------------------------------\n"); $uuid = uniqid(); $service = new DynamoDb\DynamoDBService(); $tableName = "partiql_demo_table_$uuid"; $service->createTable( $tableName, [ new DynamoDBAttribute('year', 'N', 'HASH'), new DynamoDBAttribute('title', 'S', 'RANGE') ] ); echo "Waiting for table..."; $service->dynamoDbClient->waitUntil("TableExists", ['TableName' => $tableName]); echo "table $tableName found!\n"; echo "What's the name of the last movie you watched?\n"; while (empty($movieName)) { $movieName = testable_readline("Movie name: "); } echo "And what year was it released?\n"; $movieYear = "year"; while (!is_numeric($movieYear) || intval($movieYear) != $movieYear) { $movieYear = testable_readline("Year released: "); } $key = [ 'Item' => [ 'year' => [ 'N' => "$movieYear", ], 'title' => [ 'S' => $movieName, ], ], ]; list($statement, $parameters) = $service->buildStatementAndParameters("INSERT", $tableName, $key); $service->insertItemByPartiQL($statement, $parameters); echo "How would you rate the movie from 1-10?\n"; $rating = 0; while (!is_numeric($rating) || intval($rating) != $rating || $rating < 1 || $rating > 10) { $rating = testable_readline("Rating (1-10): "); } echo "What was the movie about?\n"; while (empty($plot)) { $plot = testable_readline("Plot summary: "); } $attributes = [ new DynamoDBAttribute('rating', 'N', 'HASH', $rating), new DynamoDBAttribute('plot', 'S', 'RANGE', $plot), ]; list($statement, $parameters) = $service->buildStatementAndParameters("UPDATE", $tableName, $key, $attributes); $service->updateItemByPartiQL($statement, $parameters); echo "Movie added and updated.\n"; $batch = json_decode(loadMovieData()); $service->writeBatch($tableName, $batch); $movie = $service->getItemByPartiQL($tableName, $key); echo "\nThe movie {$movie['Items'][0]['title']['S']} was released in {$movie['Items'][0]['year']['N']}.\n"; echo "What rating would you like to give {$movie['Items'][0]['title']['S']}?\n"; $rating = 0; while (!is_numeric($rating) || intval($rating) != $rating || $rating < 1 || $rating > 10) { $rating = testable_readline("Rating (1-10): "); } $attributes = [ new DynamoDBAttribute('rating', 'N', 'HASH', $rating), new DynamoDBAttribute('plot', 'S', 'RANGE', $plot) ]; list($statement, $parameters) = $service->buildStatementAndParameters("UPDATE", $tableName, $key, $attributes); $service->updateItemByPartiQL($statement, $parameters); $movie = $service->getItemByPartiQL($tableName, $key); echo "Okay, you have rated {$movie['Items'][0]['title']['S']} as a {$movie['Items'][0]['rating']['N']}\n"; $service->deleteItemByPartiQL($statement, $parameters); echo "But, bad news, this was a trap. That movie has now been deleted because of your rating...harsh.\n"; echo "That's okay though. The book was better. Now, for something lighter, in what year were you born?\n"; $birthYear = "not a number"; while (!is_numeric($birthYear) || $birthYear >= date("Y")) { $birthYear = testable_readline("Birth year: "); } $birthKey = [ 'Key' => [ 'year' => [ 'N' => "$birthYear", ], ], ]; $result = $service->query($tableName, $birthKey); $marshal = new Marshaler(); echo "Here are the movies in our collection released the year you were born:\n"; $oops = "Oops! There were no movies released in that year (that we know of).\n"; $display = ""; foreach ($result['Items'] as $movie) { $movie = $marshal->unmarshalItem($movie); $display .= $movie['title'] . "\n"; } echo ($display) ?: $oops; $yearsKey = [ 'Key' => [ 'year' => [ 'N' => [ 'minRange' => 1990, 'maxRange' => 1999, ], ], ], ]; $filter = "year between 1990 and 1999"; echo "\nHere's a list of all the movies released in the 90s:\n"; $result = $service->scan($tableName, $yearsKey, $filter); foreach ($result['Items'] as $movie) { $movie = $marshal->unmarshalItem($movie); echo $movie['title'] . "\n"; } echo "\nCleaning up this demo by deleting table $tableName...\n"; $service->deleteTable($tableName); } } public function insertItemByPartiQL(string $statement, array $parameters) { $this->dynamoDbClient->executeStatement([ 'Statement' => "$statement", 'Parameters' => $parameters, ]); } public function getItemByPartiQL(string $tableName, array $key): Result { list($statement, $parameters) = $this->buildStatementAndParameters("SELECT", $tableName, $key['Item']); return $this->dynamoDbClient->executeStatement([ 'Parameters' => $parameters, 'Statement' => $statement, ]); } public function updateItemByPartiQL(string $statement, array $parameters) { $this->dynamoDbClient->executeStatement([ 'Statement' => $statement, 'Parameters' => $parameters, ]); } public function deleteItemByPartiQL(string $statement, array $parameters) { $this->dynamoDbClient->executeStatement([ 'Statement' => $statement, 'Parameters' => $parameters, ]); }

서버리스 예제

다음 코드 예제는 DynamoDB 스트림에서 레코드를 수신하여 트리거되는 이벤트를 수신하는 Lambda 함수를 구현하는 방법을 보여줍니다. 이 함수는 DynamoDB 페이로드를 검색하고 레코드 콘텐츠를 로깅합니다.

PHP용 SDK
참고

자세한 내용은 다음과 같습니다. GitHub 서버리스 예제 리포지토리에서 전체 예제를 찾아보고 설정 및 실행 방법을 알아봅니다.

Lambda를 사용하여 DynamoDB 이벤트를 소비합니다. PHP

<?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);

다음 코드 예제는 DynamoDB 스트림으로부터 이벤트를 수신하는 Lambda 함수에 대한 부분 배치 응답을 구현하는 방법을 보여줍니다. 이 함수는 응답으로 배치 항목 실패를 보고하고 나중에 해당 메시지를 다시 시도하도록 Lambda에 신호를 보냅니다.

PHP용 SDK
참고

자세한 내용은 다음과 같습니다. GitHub 서버리스 예제 리포지토리에서 전체 예제를 찾아보고 설정 및 실행 방법을 알아봅니다.

Lambda를 사용하여 DynamoDB 배치 항목 장애를 보고합니다. PHP

<?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);