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

  • Credentials
  • Including the SDK¶
  • Creating a client object¶
  • Factory method¶
  • Service builder¶
  • Performing service operations¶
  • Working with modeled responses¶
  • Detecting and handling errors¶
  • Iterators¶

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.

// Đoạn mã mẫu bên dưới sẽ minh họa cách thức hoạt động của các API tài nguyên

$aws = new Aws($config);

// Lấy tham chiếu đến đối tượng tài nguyên

$bucket = $aws->s3->bucket('my-bucket');

$object = $bucket->object('image/bird.jpg');

// Truy cập thuộc tính của tài nguyên

echo $object['LastModified'];

// Ra lệnh cho phương pháp của tài nguyên thực hiện thao tác

$object->delete();

$bucket->delete();

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.

Credentials

Before 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

  • Amazon CloudFront examples
  • Amazon CloudSearch
  • Amazon CloudWatch examples
  • Amazon EC2 examples
  • Amazon OpenSearch Service
  • AWS Identity and Access Management examples
  • AWS Key Management Service
  • Kinesis examples
  • AWS Elemental MediaConvert
  • Amazon S3 examples
  • AWS Secrets Manager
  • Amazon SES examples
  • Amazon SNS examples
  • Amazon SQS examples

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 /path/to/ with the actual path on your system.

Installation TechniqueInclude Statement
Using Composer require '/path/to/vendor/autoload.php';
Using the Phar require '/path/to/aws.phar';
Using the Zip require '/path/to/aws-autoloader.php';

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 factory() method and provide your credential profile (via the profile option), which identifies the set of credentials you want to use from your ~/.aws/credentials file (see Using the AWS credentials file and credential profiles).

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 AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY environment variables. For more information about credentials, see Providing Credentials to the SDK.

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 factory() method. The region value is used by the SDK to determine the regional endpoint to use to communicate with the service. Amazon S3 does not require you to provide a region, but other services like Amazon Elastic Compute Cloud (Amazon EC2) do. You can specify a region and other configuration settings along with your credentials in the array argument that you provide.

$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 Aws\Common\Aws object (a.k.a the service builder). The Aws object is essentially a service locator, and allows you to specify credentials and configuration settings such that they can be shared across all client instances. Also, every time you fetch a client object from the Aws object, it will be exactly the same instance.

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 Aws object.

// 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 Aws\DynamoDb\DynamoDbClient::describeTable() method. Operation methods, like describeTable(), all accept a single argument that is an associative array of values representing the parameters to the operation. The structure of this array is defined for each operation in the SDK's API Documentation (e.g., see the API docs for describeTable()).

$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 (Guzzle\Service\Resource\Model) object. The Model class is a part of the SDK's underlying Guzzle library, but you do not need to know anything about Guzzle to use your operation results. The Model object contains the data from the response and can be used like an array (e.g., $result['Table']). It also has convenience methods like get(), getPath(), and toArray(). The contents of the modeled response depend on the operation that was executed and are documented in the API docs for each operation (e.g., see the Returns section in the API docs for the DynamoDB DescribeTable operation).

$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 try/catch blocks around your operations if you need to handle errors in your code. The SDK throws service-specific exceptions when a server-side error occurs.

In the following example, the Aws\S3\S3Client is used. If there is an error, the exception thrown will be of the type: Aws\S3\Exception\S3Exception.

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 ServiceResponseException class (see the API docs), which has some custom methods that might help you discover what went wrong. This includes the getAwsErrorCode() method, that gives you the custom error code that can be used to explain the error.

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 "waitUntil" will create and invoke a Waiter.

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 Iterator interface, which allows you to easily enumerate or iterate through resources from a result set with foreach.

Operations that start with List or Describe, or any other operations that are designed to return multiple records can be used with Iterators. To use an Iterator, you must call the getIterator() method of the client and provide the operation name. The following is an example of creating an Amazon S3 ListObjects Iterator, to iterate over objects in a bucket.

$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.