Skip to content

Commit

Permalink
Updated the upper portion of the migration guide.
Browse files Browse the repository at this point in the history
  • Loading branch information
jeremeamia committed May 2, 2015
1 parent 14136ac commit 1bcd0bc
Showing 1 changed file with 63 additions and 209 deletions.
272 changes: 63 additions & 209 deletions docs/guide/migration.rst
Expand Up @@ -2,103 +2,87 @@
Migration Guide
===============

This guide shows how to migrate your code to use the new AWS SDK for PHP and how the new SDK differs from the
AWS SDK for PHP - Version 1.
This guide shows how to migrate your code to use version 3 of the AWS SDK for
PHP and how the new version differs from the version 2 of the SDK.

Introduction
------------

The PHP language and community have evolved significantly over the past few years. Since the inception of the AWS SDK
for PHP, PHP has gone through two major version changes (`versions 5.3 and 5.4 <http://php.net/downloads.php#v5>`_) and
many in the PHP community have unified behind the recommendations of the `PHP Framework Interop Group
<http://php-fig.org>`_. Consequently, we decided to make breaking changes to the SDK in order to align with the more
modern patterns used in the PHP community.
.. note::

For the new release, we rewrote the SDK from the ground up to address popular customer requests. The new SDK is built on
top of the `Guzzle HTTP client framework <http://guzzlephp.org>`_, which provides increased performance and enables
event-driven customization. We also introduced high-level abstractions to make programming common tasks easy. The SDK
is compatible with PHP 5.3.3 and newer, and follows the PSR-0 standard for namespaces and autoloading.
The basic usage pattern of the SDK (i.e., ``$result = $client->operation($params);``)
has not changed from version 2 to version 3. This should result in a fairly
smooth migration.

Which Services are Supported?
-----------------------------
Introduction
------------

The AWS SDK for PHP supports all of the AWS services supported by Version 1 of the SDK and more, including Amazon
Route 53, Amazon Glacier, and AWS Direct Connect. See the `AWS SDK for PHP website <http://aws.amazon.com/sdkforphp/>`_
for the full list of services supported by the SDK. Be sure to watch or star our `AWS SDK for PHP GitHub repository
<https://github.com/aws/aws-sdk-php>`_ to stay up-to-date with the latest changes.
Version 3 of the SDK represents a significant effort to improve the capabilities
of the SDK, incorporate 2 years of customer feedback, upgrade our dependencies,
and adopt the latest PHP standards.

What's New?
-----------

- `PHP 5.3 namespaces <http://php.net/namespaces>`_
- Follows `PSR-0, PSR-1, and PSR-2 standards <http://php-fig.org>`_
- Built on `Guzzle <http://guzzlephp.org>`_ and utilizes the Guzzle feature set
- Persistent connection management for both serial and parallel requests
- Event hooks (via `Symfony2 EventDispatcher
<http://symfony.com/doc/2.0/components/event_dispatcher/introduction.html>`_) for event-driven, custom behavior
- Request and response entity bodies are stored in ``php://temp`` streams to reduce memory usage
- Transient networking and cURL failures are automatically retried using truncated exponential backoff
- Plug-ins for over-the-wire logging and response caching
- "Waiter" objects that allow you to poll a resource until it is in a desired state
- Resource iterator objects for easily iterating over paginated responses
- Service-specific sets of exceptions
- Modeled responses with a simpler interface
- Grouped constants (Enums) for service parameter options
- Flexible request batching system
- Service builder/container that supports easy configuration and dependency injection
- Full unit test suite with extensive code coverage
- `Composer <http://getcomposer.org>`_ support (including PSR-0 compliance) for installing and autoloading SDK
dependencies
- `Phing <http://phing.info>`_ ``build.xml`` for installing dev tools, driving testing, and producing ``.phar`` files
- Fast Amazon DynamoDB batch PutItem and DeleteItem system
- Multipart upload system for Amazon Simple Storage Service (Amazon S3) and Amazon Glacier that can be paused and
resumed
- Redesigned DynamoDB Session Handler with smarter writing and garbage collection
- Improved multi-region support
- Follows the `PSR-4 and PSR-7 standards <http://php-fig.org>`_
- Built on `Guzzle 6 <http://guzzlephp.org>`_.
- Decoupled HTTP layer so that Guzzle 5 is also supported.
- Swappable HTTP handlers, including non-cURL options like a PHP stream
wrapper handler.
- Asynchronous requests.
- Features like *waiters* and *multipart uploaders* can be used asynchronously.
- Asynchronous workflows can be created using *promises* and *coroutines*.
- Improved performance of concurrent/batched requests.
- Middleware system for customizing service client behavior.
- Flexible *paginators* for iterating through paginated results.
- Ability to query data from *result* and *paginator* objects with *JMESPath*.
- Easy debugging via the ``'debug'`` configuration option.

What's Different?
-----------------

Architecture
~~~~~~~~~~~~

The new SDK is built on top of `Guzzle <http://guzzlephp.org>`_ and inherits its features and
conventions. Every AWS service client extends the Guzzle client, defining operations through a service description
file. The SDK has a much more robust and flexible object-oriented architecture, including the use of design patterns,
event dispatching and dependency injection. As a result, many of the classes and methods from the previous SDK have
been changed.

Project Dependencies
~~~~~~~~~~~~~~~~~~~~

Unlike the Version 1 of the SDK, the new SDK does not pre-package all of its dependencies
in the repository. Dependencies are best resolved and autoloaded via `Composer <http://getcomposer.org>`_. However,
when installing the SDK via the downloadable phar, the dependencies are resolved for you.

Namespaces
~~~~~~~~~~

The SDK's directory structure and namespaces are organized according to `PSR-0 standards
<https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-0.md>`_, making the SDK inherently modular. The
``Aws\Common`` namespace contains the core code of the SDK, and each service client is contained in its own separate
namespace (e.g., ``Aws\DynamoDb``).

Coding Standards
~~~~~~~~~~~~~~~~

The SDK adopts the PSR standards produced by the PHP Framework Interop Group. An immediately
noticeable change is that all method names are now named using lower camel-case
(e.g., ``putObject`` instead of ``put_object``).

Required Regions
~~~~~~~~~~~~~~~~
The dependencies of the SDK have changed a little in this version.

- The SDK now requires PHP 5.5+. We use `generators <http://php.net/manual/en/language.generators.overview.php>`_
liberally within the SDK code.
- We've upgraded the SDK to use `Guzzle 6 <http://guzzlephp.org>`_ (or 5), which
provides the underlying HTTP client implementation used by the SDK to send
requests to the AWS services. The latest version of Guzzle brings with it a
number of improvements, including asynchronous requests, swappable HTTP
handlers, PSR-7 compliance, better performance, and more.
- The PSR-7 package from the PHP-FIG (``psr/http-message``) defines interfaces
for representing HTTP requests, HTTP responses, URLs, and streams. These
interfaces are used across the SDK and Guzzle, which provides interoperability
with other PSR-7 compliant packages.
- Guzzle's PSR-7 implementation (``guzzlehttp/psr7``) provides an implementation
of the interfaces in PSR-7, as well as a number of helpful classes and
functions to go along with it. Both the SDK and Guzzle 6 rely on this package
heavily.
- Guzzle's `Promises/A+ <https://promisesaplus.com/>`_ implementation
(``guzzlehttp/promises``) is used throughout the SDK and Guzzle to provide
interfaces for managing asynchronous requests and coroutines. While Guzzle's
multi-cURL HTTP handler ultimately implements the non-blocking I/O model that
allows for asynchronous requests, this package provides the ability to program
within that paradigm.
- The PHP implementation of JMESPath (``mtdowling/jmespath.php``) is used in the
SDK to provide the data querying ability of the ``Aws\Result::search()`` and
``Aws\ResultPaginator::search()``.

====

.. note::

The remainder of this guide is still being updated.

Required Regions & Versions
~~~~~~~~~~~~~~~~~~~~~~~~~~~

The `region <http://docs.aws.amazon.com/general/latest/gr/rande.html>`_ must be provided to instantiate a client
(except in the case where the service has a single endpoint like Amazon CloudFront). The AWS region you select may
affect both your performance and costs.

Client Factories
~~~~~~~~~~~~~~~~
Client Instantiation
~~~~~~~~~~~~~~~~~~~~

Factory methods instantiate service clients and do the work of setting up the signature,
exponential backoff settings, exception handler, and so forth. At a minimum you must provide your access key, secret
Expand All @@ -113,8 +97,8 @@ behavior.
'region' => 'us-west-2',
));
Configuration
~~~~~~~~~~~~~
Client Configuration
~~~~~~~~~~~~~~~~~~~~

A global configuration file can be used to inject credentials into clients
automatically via the service builder. The service builder acts as a dependency injection container for the service
Expand Down Expand Up @@ -149,136 +133,6 @@ The line that says ``'includes' => array('_aws')`` includes the default configur
sets up all of the service clients for you so you can retrieve them by name with the ``get()`` method of the service
builder.

Service Operations
~~~~~~~~~~~~~~~~~~

Executing operations in the new SDK is similar to how it was in the previous SDK, with two
main differences. First, operations follow the lower camel-case naming convention. Second, a single array parameter is
used to pass in all of the operation options. The following examples show the Amazon S3 ``PutObject`` operation
performed in each SDK:

.. code-block:: php
// Previous SDK - PutObject operation
$s3->create_object('bucket-name', 'object-key.txt', array(
'body' => 'lorem ipsum'
));
.. code-block:: php
// New SDK - PutObject operation
$result = $s3->putObject(array(
'Bucket' => 'bucket-name',
'Key' => 'object-key.txt',
'Body' => 'lorem ipsum'
));
In the new SDK, the ``putObject()`` method doesn't actually exist as a method on the client. It is implemented using
the ``__call()`` magic method of the client and acts as a shortcut to instantiate a command, execute the command,
and retrieve the result.

A ``Command`` object encapsulates the request and response of the call to AWS. From the ``Command`` object, you can
call the ``getResult()`` method (as in the preceding example) to retrieve the parsed result, or you can call the
``getResponse()`` method to retrieve data about the response (e.g., the status code or the raw response).

The ``Command`` object can also be useful when you want to manipulate the command before execution or need to execute
several commands in parallel. The following is an example of the same ``PutObject`` operation using the command
syntax:

.. code-block:: php
$command = $s3->getCommand('PutObject', array(
'Bucket' => 'bucket-name',
'Key' => 'object-key.txt',
'Body' => 'lorem ipsum'
));
$result = $command->getResult();
Or you can use the chainable ``set()`` method on the ``Command`` object:

.. code-block:: php
$result = $s3->getCommand('PutObject')
->set('Bucket', 'bucket-name')
->set('Key', 'object-key.txt')
->set('Body', 'lorem ipsum')
->getResult();
Responses
~~~~~~~~~

The format of responses has changed. Responses are no longer instances of the ``CFResponse`` object.
The ``Command`` object (as seen in the preceding section) of the new SDK encapsulates the request and response, and is
the object from which to retrieve the results.

.. code-block:: php
// Previous SDK
// Execute the operation and get the CFResponse object
$response = $s3->list_tables();
// Get the parsed response body as a SimpleXMLElement
$result = $response->body;
// New SDK
// Executes the operation and gets the response in an array-like object
$result = $s3->listTables();
The new syntax is similar, but a few fundamental differences exist between responses in the previous SDK and this
version:

The new SDK represents parsed responses (i.e., the results) as Guzzle ``Model`` objects instead of ``CFSimpleXML``
objects as in the prior version. These Model objects are easy to work with since they act like arrays. They also
have helpful built-in features such as mapping and filtering. The content of the results will also look different
n this version of the SDK. The SDK marshals responses into the models and then transforms them into more convenient
structures based on the service description. The API documentation details the response of all operations.

Exceptions
~~~~~~~~~~

The new SDK uses exceptions to communicate errors and bad responses.

Instead of relying on the ``CFResponse::isOK()`` method of the previous SDK to determine if an operation is
successful, the new SDK throws exceptions when the operation is *not* successful. Therefore, you can assume success
if there was no exception thrown, but you will need to add ``try...catch`` logic to your application code in order to
handle potential errors. The following is an example of how to handle the response of an Amazon DynamoDB
``DescribeTable`` call in the new SDK:

.. code-block:: php
$tableName = 'my-table';
try {
$result = $dynamoDb->describeTable(array('TableName' => $tableName));
printf('The provisioned throughput for table "%s" is %d RCUs and %d WCUs.',
$tableName,
$result->getPath('Table/ProvisionedThroughput/ReadCapacityUnits'),
$result->getPath('Table/ProvisionedThroughput/WriteCapacityUnits')
);
} catch (Aws\DynamoDb\Exception\DynamoDbException $e) {
echo "Error describing table {$tableName}";
}
You can get the Guzzle response object back from the command. This is helpful if you need to retrieve the status
code, additional data from the headers, or the raw response body.

.. code-block:: php
$command = $dynamoDb->getCommand('DescribeTable', array('TableName' => $tableName));
$statusCode = $command->getResponse()->getStatusCode();
You can also get the response object and status code from the exception if one is thrown.

.. code-block:: php
try {
$command = $dynamoDb->getCommand('DescribeTable', array(
'TableName' => $tableName
));
$statusCode = $command->getResponse()->getStatusCode();
} catch (Aws\DynamoDb\Exception\DynamoDbException $e) {
$statusCode = $e->getResponse()->getStatusCode();
}
Iterators
~~~~~~~~~

Expand Down

0 comments on commit 1bcd0bc

Please sign in to comment.