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

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

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

本主题主要介绍 Amazon 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';

在此主题中,我们假设了 Composer 安装方法。如果您使用其他安装方法,可以回到这一部分来查找应使用的正确 require 代码。

用法总结

要使用 SDK 与 Amazon 服务进行交互,需将客户端对象实例化。客户端对象包含与服务 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'.

有关可选“版本”参数的信息,请参阅配置选项主题。

请注意,我们并未向客户端显式提供凭证。这是因为 SDK 应从环境变量、主目录中的 共享 config 和 credentials 文件、Amazon Identity and Access Management (IAM) 实例配置文件凭证凭证提供程序中检测凭证。

Amazon SDK for PHP 版本 3 的配置 中详细介绍了所有通用的客户端配置选项。创建的客户端不同,提供的选项数组也不同。每个客户端的 API 文档中介绍了这些自定义客户端配置选项。

使用 Sdk

Aws\Sdk 类可作为客户端工厂,用于管理多个客户端的共享配置选项。许多可提供给特定客户端构造函数的选项也可提供给 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();

所有客户端均可共享的选项置于根级别的键值对中。可在与服务命名空间相同的键(例如“S3”、“DynamoDb”等)中提供特定于服务的配置数据。

$sdk = new Aws\Sdk([ 'region' => 'us-west-2', 'DynamoDb' => [ 'region' => 'eu-central-1' ] ]); // Creating an Amazon DynamoDb client will use the "eu-central-1" Amazon 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”“latest”)。开发工具包会根据提供的版本找到相应的配置文件。

所有操作方法 (如 putObject()) 均接受单独的参数,或代表操作参数的关联数组。此数组的结构(以及结果对象的结构)是在开发工具包的 API 文档中针对每个操作进行定义的(例如,请参阅 API 文档中的 putObject 操作)。

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 后缀,异步发送请求。这样可以启动请求并返回 Promise。如果成功,结果对象可满足 Promise;如果失败,异常会导致拒绝 Promise。您可以创建多个 Promise,并由它们在底层 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();

您可以使用 Promise 的 wait 方法,强制 Promise 同步完成。默认情况下,强制完成 Promise 也会“解封”Promise 的状态,这意味着它会返回 Promise 的结果或引发异常。如果针对 Promise 调用 wait(),流程将会阻塞,直到 HTTP 请求完成并填充结果,或引发异常。

如果使用具有事件循环库的开发工具包,请不要阻塞结果。请使用结果的 then() 方法,在操作完成时访问已解决或被拒绝的 Promise。

导入

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(); });

使用 Result 对象

执行成功的操作会返回 Aws\Result 对象。开发工具包不会返回服务的原始 XML 或 JSON 数据,而是会将响应数据强制加入关联数组结构中。这样可以根据它对特定服务和底层响应结构的认知,将数据的某些方面规范化。

您可以访问 AWSResult 对象的数据,就像访问关联 PHP 数组那样。

导入

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 集成,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()); }

异步处理错误

在发送异步请求的时候不会引发异常。您必须使用返回的 Promise 的 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(); }