Cees-Jan

AWS PHP SDK Asynchronously

Just got off the AWS SDK for PHP Office Hour hangout and it was great talking with both team members Jeremy and Michael. And one of the things we talked about was async access to the AWS services using the PHP SDK.

The goal of this post is to get the AWS PHP SDK client working asynchronously.

Requirements

To get started we need two things:

Setting up the SDK

To setup the SDK we need a few ingredients that we pulled in installing the SDK and my adapter:

The event loop is needed by the handler that is passed into the Guzze's handler stack. Now note that we pass the handler stack into the SDK as the HTTP handler option. That tells the SDK to use Guzzle instead of creating it's own HTTP handler. (You also still have to pass credentials.)

<?php

use Aws\Result;
use Aws\Sdk;
use GuzzleHttp\HandlerStack;
use React\EventLoop\Factory
use WyriHaximus\React\GuzzlePsr7\HttpClientAdapter;

require 'vendor/autoload.php';

$loop = Factory::create();
$sdk = new Sdk([
    'http_handler' => HandlerStack::create(new HttpClientAdapter($loop)),
]);
Making async calls

Now that we have the SDK setup to do async calls lets, as example, fetch an object from S3 and echo it's body:

$sdk->createS3()->getObjectAsync([
    'Bucket' => 'yourbucket',
    'Key' => 'path/to/file.ext',
])->then(function (Result $result) {
    echo $result['Body'], PHP_EOL;
});

Note that we appended Async behind the getObject function to ensure it returns a promise.

Demo

The following is a recording of a directory listing on the S3 bucket of my blog using the wyrihaximus/react-filesystem-s3 adapter for react/filesystem I'm working on. On a side note the listing was done on a moving train through a 3G connection so it might look slow but that is due to the connection. Over a normal wifi or cable connection it is done within 2 to 3 seconds topping at 100 request a second.


Categories: PHP - ReactPHP - AWSTags: PHP - ReactPHP - AWS