第 3 AWS SDK for PHP 版的基本使用模式 - AWS SDK for PHP

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

第 3 AWS SDK for PHP 版的基本使用模式

本主題聚焦於AWS SDK for PHP的基本使用模式。

先決條件

在程式碼中包含 SDK

無論您使用何種技術來安裝開發套件,您只需使用單一 require 陳述式在程式碼中加入開發套件。請參閱下表中來找到最適用於您的安裝技術之 PHP 程式碼。以系統上的實際路徑來替換任何 /path/to/ 的執行個體。

安裝技術 需要陳述式

使用 Composer

require '/path/to/vendor/autoload.php';

使用 phar

require '/path/to/aws.phar';

使用 ZIP

require '/path/to/aws-autoloader.php';

在本主題中,我們假設作曲家安裝方法。若您正在使用不同的安裝方法,您可以重新參考本節來尋找要使用的正確 require 程式碼。

用法摘要

若要使用 SDK 與AWS服務互動,請實體化用戶端物件。客戶端對象具有與服務 API 中的操作相對應的方法。若要執行特定的操作,請呼叫其對應的方法。這個方法會在成功時傳回如陣列般的結果物件,或在失敗時丟出例外

建立用戶端

您可以藉由將選項的關聯陣列傳遞至用戶端的建構函數,來建立用戶端。

匯入

require 'vendor/autoload.php'; use Aws\S3\S3Client; use Aws\Exception\AwsException;

範例程式碼

//Create an S3Client $s3 = new Aws\S3\S3Client([ 'region' => 'us-east-2' // Since version 3.277.10 of the SDK, ]); // the 'version' parameter defaults to 'latest'.

組態選項主題中提供選用「version」參數的相關資訊。

請注意,我們並未明確提供登入資料給用戶端。這是因為 SDK 應該偵測來自環境變數、HOME 目錄共用config和credentials檔案中、AWS Identity and Access Management (IAM) 執行個體設定檔登入資料認證提供者的登入資料。

所有一般用戶端組態選項都會在中詳細說明AWS SDK for PHP版本 3 的組態。提供給用戶端的選項陣列可能會因您正在建立的用戶端而不同。這些自訂用戶端組態選項的說明如各用戶端的 API 文件所述。

使用Sdk類別

Aws\Sdk 類別做為用戶端 factory,用於管理跨多個用戶端的共用組態選項。許多可以提供給特定客戶端構造函數的選項也可以提供給Aws\Sdk類。這些選項接著會套用到每個用戶端建構函式。

匯入

require 'vendor/autoload.php'; use Aws\S3\S3Client; use Aws\Exception\AwsException;

範例程式碼

// The same options that can be provided to a specific client constructor can also be supplied to the Aws\Sdk class. // Use the us-west-2 region and latest version of each client. $sharedConfig = [ 'region' => 'us-west-2' ]; // Create an SDK class used to share configuration across clients. $sdk = new Aws\Sdk($sharedConfig); // Create an Amazon S3 client using the shared configuration data. $client = $sdk->createS3();

在所有用戶端共用的選項將放入根層級的金鑰值組。服務特定組態資料可以在與服務命名空間相同的金鑰中提供 (例如「S3DynamoDb」、「」等)。

$sdk = new Aws\Sdk([ 'region' => 'us-west-2', 'DynamoDb' => [ 'region' => 'eu-central-1' ] ]); // Creating an Amazon DynamoDb client will use the "eu-central-1" AWS Region $client = $sdk->createDynamoDb();

服務特定的組態值為服務特定值與根層級值的整合 (即服務特定值以淺層合併至根層級值)。

注意

如果您正在您的應用程式中使用多個用戶端執行個體,我們強烈建議您使用 Sdk 類別。Sdk 類別自動為各開發套件用戶端使用相同的 HTTP 用戶端,讓不同服務的開發套件用戶端執行非鎖定 HTTP 請求。如果軟體開發套件用戶端不使用相同的 HTTP 用戶端,則由軟體開發套件用戶端傳送的 HTTP 請求可能會封鎖服務之間的 promise 協同。

執行服務作業

您可以透過在用戶端物件上呼叫相同名稱的方法來執行服務操作。例如,若要執行 Amazon S3 PutObject作業,您必須呼叫該Aws\S3\S3Client::putObject()方法。

匯入

require 'vendor/autoload.php'; use Aws\S3\S3Client;

範例程式碼

// Use the us-east-2 region and latest version of each client. $sharedConfig = [ 'profile' => 'default', 'region' => 'us-east-2' ]; // Create an SDK class used to share configuration across clients. $sdk = new Aws\Sdk($sharedConfig); // Use an Aws\Sdk class to create the S3Client object. $s3Client = $sdk->createS3(); // Send a PutObject request and get the result object. $result = $s3Client->putObject([ 'Bucket' => 'my-bucket', 'Key' => 'my-key', 'Body' => 'this is the body!' ]); // Download the contents of the object. $result = $s3Client->getObject([ 'Bucket' => 'my-bucket', 'Key' => 'my-key' ]); // Print the body of the result by indexing into the result object. echo $result['Body'];

用戶端可使用的操作以及輸入與輸出的結構皆根據服務描述檔在執行時間時定義。建立用戶端時,您必須提供版本 (例如「2006-03-01」或「最新」)。開發套件根據提供的版本找到對應的組態檔案。

putObject() 的操作方法皆接受陳述式,為代表操作參數的相關陣列。此陣列的結構 (以及結果物件的結構) 已為軟體開發套件 API 文件中的各項操作定義 (例如,請參閱 putObject 操作的 API 文件)。

HTTP 處理常式選項

您也可以使用特殊 @http 參數來微調基礎 HTTP 處理常式如何執行請求。您可以在 @http 參數中包含的選項與您在使用 “http” 用戶端選項執行個體化用戶端時可設定的選項相同。

// Send the request through a proxy $result = $s3Client->putObject([ 'Bucket' => 'my-bucket', 'Key' => 'my-key', 'Body' => 'this is the body!', '@http' => [ 'proxy' => 'http://192.168.16.1:10' ] ]);

非同步請求

您可以使用開發套件的非同步功能來同時傳送命令。您可以在操作名稱中加入 Async 前綴來以非同步方式傳送請求。這將啟動請求並傳回承諾。承諾以成功或以例外狀況遭拒的結果物件履行。這可讓您建立多個承諾,並在基礎 HTTP 處理常式傳輸請求時讓它們同時傳送 HTTP 請求。

匯入

require 'vendor/autoload.php'; use Aws\S3\S3Client; use Aws\Exception\AwsException;

範例程式碼

// Create an SDK class used to share configuration across clients. $sdk = new Aws\Sdk([ 'region' => 'us-west-2' ]); // Use an Aws\Sdk class to create the S3Client object. $s3Client = $sdk->createS3(); //Listing all S3 Bucket $CompleteSynchronously = $s3Client->listBucketsAsync(); // Block until the result is ready. $CompleteSynchronously = $CompleteSynchronously->wait();

您可以透過使用承諾的 wait 方法同步強制承諾完成。強制 promise 完成的同時也會根據預設「取消包裝」promise 的狀態,表示其會傳回 promise 的結果或者拋出遇到的例外狀況。在承諾上呼叫 wait() 時,直到 HTTP 請求完成且發布結果或丟出例外狀況前,處理程序皆會封鎖。

以事件迴圈程式庫來使用軟體開發套件時,請不要封鎖結果。相反地,請使用結果的 then() 方法來存取在操作完成時解決或拒絕的承諾。

匯入

require 'vendor/autoload.php'; use Aws\S3\S3Client; use Aws\Exception\AwsException;

範例程式碼

// Create an SDK class used to share configuration across clients. $sdk = new Aws\Sdk([ 'region' => 'us-west-2' ]); // Use an Aws\Sdk class to create the S3Client object. $s3Client = $sdk->createS3();
$promise = $s3Client->listBucketsAsync(); $promise ->then(function ($result) { echo 'Got a result: ' . var_export($result, true); }) ->otherwise(function ($reason) { echo 'Encountered an error: ' . $reason->getMessage(); });

使用結果物件

執行成功操作會傳回 Aws\Result 物件。除了傳回原始 XML 或服務的 JSON 資料外,開發套件會強迫回應資料變為關聯性的陣列結構。將根據對於特定服務的知識以及基礎回應結構來標準化資料中的部分面向。

您可以像關聯 PHP 數組一樣從 AWSResult 對象訪問數據。

匯入

require 'vendor/autoload.php'; use Aws\S3\S3Client; use Aws\Exception\AwsException;

範例程式碼

// Use the us-east-2 region and latest version of each client. $sharedConfig = [ 'profile' => 'default', 'region' => 'us-east-2', ]; // Create an SDK class used to share configuration across clients. $sdk = new Aws\Sdk($sharedConfig); // Use an Aws\Sdk class to create the S3Client object. $s3 = $sdk->createS3(); $result = $s3->listBuckets(); foreach ($result['Buckets'] as $bucket) { echo $bucket['Name'] . "\n"; } // Convert the result object to a PHP array $array = $result->toArray();

結果物件的內容會根據執行的操作以及服務版本而定。每個 API 操作的結果結構將根據各操作記錄於 API 文件中。

開發套件與 JMESPath 整合,此 DSL 用於搜尋及操控 JSON 資料,即如同本文件用於操控 PHP 陣列。結果物件包含您可以用於更明顯宣告從結果中擷取資料的 search() 方法。

範例程式碼

$s3 = $sdk->createS3(); $result = $s3->listBuckets();
$names = $result->search('Buckets[].Name');

處理錯誤

同步錯誤處理

執行操作時若發生錯誤,將顯示例外情況。因此,如果您需要處理程式碼中的錯誤,請在操作周圍使用 try/catch 區塊。開發套件發生錯誤時將丟出服務專屬的例外狀況。

下列為使用 Aws\S3\S3Client 的範例。如果發生錯誤,丟出的例外狀況將會是類型 Aws\S3\Exception\S3Exception。所有開發套件丟出的服務專屬的例外狀況皆從 Aws\Exception\AwsException 延伸而來。此類別包含關於失敗的實用資訊,包括請求 ID、錯誤碼和錯誤類型。請注意,對於某些支援它的服務,回應資料會強制轉換為關聯陣列結構 (類似於 Aws\Result 物件),此資料可以如何一般 PHP 關聯陣列一樣進行存取。toArray() 方法將傳回任何這類資料,如果存在的話。

匯入

require 'vendor/autoload.php'; use Aws\S3\S3Client; use Aws\Exception\AwsException; use Aws\S3\Exception\S3Exception;

範例程式碼

// Create an SDK class used to share configuration across clients. $sdk = new Aws\Sdk([ 'region' => 'us-west-2' ]); // Use an Aws\Sdk class to create the S3Client object. $s3Client = $sdk->createS3(); try { $s3Client->createBucket(['Bucket' => 'my-bucket']); } catch (S3Exception $e) { // Catch an S3 specific exception. echo $e->getMessage(); } catch (AwsException $e) { // This catches the more generic AwsException. You can grab information // from the exception using methods of the exception object. echo $e->getAwsRequestId() . "\n"; echo $e->getAwsErrorType() . "\n"; echo $e->getAwsErrorCode() . "\n"; // This dumps any modeled response data, if supported by the service // Specific members can be accessed directly (e.g. $e['MemberName']) var_dump($e->toArray()); }

異步錯誤處理

傳送非同步請求時不會丟出例外狀況。但是,您必須使用傳回承諾的 then()otherwise() 方法接來收結果或錯誤。

匯入

require 'vendor/autoload.php'; use Aws\S3\S3Client; use Aws\Exception\AwsException; use Aws\S3\Exception\S3Exception;

範例程式碼

//Asynchronous Error Handling $promise = $s3Client->createBucketAsync(['Bucket' => 'my-bucket']); $promise->otherwise(function ($reason) { var_dump($reason); }); // This does the same thing as the "otherwise" function. $promise->then(null, function ($reason) { var_dump($reason); });

您可以「取消包裝」promise,並拋出例外狀況。

匯入

require 'vendor/autoload.php'; use Aws\S3\S3Client; use Aws\Exception\AwsException; use Aws\S3\Exception\S3Exception;

範例程式碼

$promise = $s3Client->createBucketAsync(['Bucket' => 'my-bucket']);
//throw exception try { $result = $promise->wait(); } catch (S3Exception $e) { echo $e->getMessage(); }