Hướng dẫn aws php tutorial
Bắt đầu sử dụng nhanh chóng AWS với AWS SDK cho PHP. SDK là thư viện PHP nguồn mở hiện đại giúp bạn dễ dàng tích hợp ứng dụng PHP với các dịch vụ AWS như Amazon S3, Amazon Glacier và Amazon DynamoDB. Nội dung chính Các API tài nguyên của AWS cung cấp một phần rút gọn tập trung vào đối tượng của giao diện "cấp thấp" tức giao diện kiểu RPC trong AWS SDK cho PHP, để đem lại trải nghiệm viết mã trực quan hơn. Đối tượng tài nguyên là tham chiếu đến tài nguyên AWS (ví dụ như phiên bản Amazon EC2 hoặc đối tượng Amazon S3) tiết lộ các thuộc tính của tài nguyên và thao tác theo thuộc tính và phương pháp của đối tượng tài nguyên. Thông tin chi tiết của yêu cầu API HTTP ngầm trở nên rõ ràng và bạn sẽ được làm việc với tài nguyên AWS như thể đó là các đối tượng PHP cục bộ. Đoạn mã mẫu bên dưới sẽ minh họa cách thức hoạt động của quá trình này. Các dịch vụ được hỗ trợ gồm có Amazon EC2, Amazon S3, Amazon SNS, Amazon SQS, AWS IAM, Amazon Glacier và AWS CloudFormation, với thêm nhiều dịch vụ khác sẽ được bổ sung trong tương lai.
Bạn muốn tìm các phiên bản cũ của AWS SDK cho PHP? AWS sẽ ngừng hỗ trợ cho Internet Explorer vào 07/31/2022. Các trình duyệt được hỗ trợ là Chrome, Firefox, Edge và Safari. Tìm hiểu thêm » This section contains code examples that demonstrate common AWS scenarios that use the AWS SDK for PHP. All the example code for the AWS SDK for PHP is available here on GitHub. CredentialsBefore running the example code, configure your AWS credentials, as described in Setting credentials. Then import the AWS SDK for PHP, as described in Basic usage. Topics
Document Conventions Amazon S3 client side encryption Amazon CloudFront examples This "Getting Started Guide" focuses on basic usage of the AWS SDK for PHP. After reading through this material, you should be familiar with the SDK and be able to start using the SDK in your application. This guide assumes that you have already downloaded and installed the SDK and retrieved your AWS access keys. Including the SDK¶No matter which technique you have used to to install the SDK, the SDK can be included into your project or script with just a single include (or require) statement. Please refer to the following table for the PHP code that best fits your installation technique. Please replace any instances of
For the remainder of this guide, we will show examples that use the Composer installation method. If you are using a different installation method, then you can refer to this section and substitute in the proper code. Creating a client object¶To use the SDK, you first you need to instantiate a client object for the service you are using. We'll use the Amazon Simple Storage Service (Amazon S3) client as an example. You can instantiate a client using two different techniques. Factory method¶The easiest way to get up and running quickly is to use the web service client's php
// Include the SDK using the Composer autoloader
require 'vendor/autoload.php';
use Aws\S3\S3Client;
// Instantiate the S3 client using your credential profile
$s3Client = S3Client::factory(array(
'profile' => 'my_profile',
));
You can also choose to forgo specifying
credentials if you are relying on instance profile credentials, provided via AWS Identity and Access Management (AWS IAM) roles for EC2 instances, or environment credentials sourced from the Note Instance profile credentials and other temporary credentials generated by the AWS Security Token Service (AWS STS) are not supported by every service. Please check if the service you are using supports temporary credentials by reading AWS Services that Support AWS STS. Depending on the service, you may also need to provide a region value to the $ec2Client = \Aws\Ec2\Ec2Client::factory(array( 'profile' => 'my_profile', 'region' => 'us-east-1', )); To know if the service client you are using requires a region and to find out which regions are supported by the client, please see the appropriate service-specific guide. Service builder¶Another way to instantiate a service client is using the use Aws\Common\Aws; // Create a service locator using a configuration file $aws = Aws::factory(array( 'profile' => 'my_profile', 'region' => 'us-east-1', )); // Get client instances from the service locator by name $s3Client = $aws->get('s3'); $ec2Client = $aws->get('ec2'); // The service locator always returns the same instance $anotherS3Client = $aws->get('s3'); assert('$s3Client === $anotherS3Client'); You can also declare your credentials and settings in a configuration file, and provide the path to that file (in either php or json format) when you instantiate the
// Create a `Aws` object using a configuration file $aws = Aws::factory('/path/to/config.php'); // Get the client from the service locator by namespace $s3Client = $aws->get('s3'); A simple configuration file should look something like this: php return array(
'includes' => array('_aws'),
'services' => array(
'default_settings' => array(
'params' => array(
'profile' => 'my_profile',
'region' => 'us-west-2'
)
)
)
);
For more information about configuration files, please see Configuring the SDK. Performing service operations¶You can perform a service operation by calling the method of the same name on the client object. For example, to perform the Amazon DynamoDB DescribeTable operation, you must call the
$result = $dynamoDbClient->describeTable(array( 'TableName' => 'YourTableName', )); To learn about performing operations in more detail, including using command objects, see Command Objects. Working with modeled responses¶The result of a performing an operation is what we refer to as a modeled response. Instead of returning the raw XML or JSON data, the SDK will coerce the data into an associative array and normalize some aspects of the data based on its knowledge of the specific service and the underlying response structure. The actual value returned is a Model ( $result = $dynamoDbClient->describeTable(array( 'TableName' => 'YourTableName', )); // Get a specific value from the result $table = $result['Table']; if ($table && isset($table['TableStatus'])) { echo $table['TableStatus']; } //> ACTIVE // Get nested values from the result easily echo $result->getPath('Table/TableStatus'); //> ACTIVE // Convert the Model to a plain array var_export($result->toArray()); //> array ( 'Table' => array ( 'AttributeDefinitions' => array ( ... ) ... ) ... ) To learn more about how to work with modeled responses, read the detailed guide to Modeled Responses. Detecting and handling errors¶When you preform an operation, and it succeeds, it will return a modeled response. If there was an error with the request, then an exception is thrown. For this reason, you should use In the following example, the try { $s3Client->createBucket(array( 'Bucket' => 'my-bucket' )); } catch (\Aws\S3\Exception\S3Exception $e) { // The AWS error code (e.g., ) echo $e->getAwsErrorCode() . "\n"; // The bucket couldn't be created echo $e->getMessage() . "\n"; } Exceptions thrown by the SDK, like in the preceding example, all extend the Waiters¶One of the higher-level
abstractions provided by the SDK are Waiters. Waiters help make it easier to work with eventually consistent systems by providing an easy way to wait until a resource enters into a particular state by polling the resource. You can find a list of the waiters supported by a client by viewing the API Documentation of a service client. Any method with a name starting with " In the following example, the Amazon S3 Client is used to create a bucket. Then the Waiter is used to wait until the bucket exists. // Create a bucket $s3Client->createBucket(array('Bucket' => 'my-bucket')); // Wait until the created bucket is available $s3Client->waitUntil('BucketExists', array('Bucket' => 'my-bucket')); To learn more about how to use and configure waiters, please read the detailed guide to Waiters. Iterators¶Some AWS operations return truncated results that require subsequent requests in order to retrieve the entire result set. The subsequent requests typically require pagination tokens or markers from the previous request in order to retrieve the next set of results. Working with these tokens can be cumbersome, since you must manually keep track of them, and the API for each service you are using may differ in the names and details of the tokens. The AWS SDK for PHP has a feature called Iterators that allow you to retrieve an entire result set without manually handling pagination tokens or markers. The Iterators in the SDK implement PHP's Operations that start with $iterator = $client->getIterator('ListObjects', array('Bucket' => 'my-bucket')); foreach ($iterator as $object) { echo $object['Key'] . "\n"; } To learn more about how to use and configure iterators, please read the detailed guide to Iterators. |