Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.

(DEV305) Building Apps with the AWS SDK for PHP | AWS re:Invent 2014

6,334 views

Published on

For both new and experienced users of the AWS SDK for PHP, we highlight features of the SDK as we work through building a simple, scalable PHP application. Attendees will learn about core features of the SDK including service clients, iterators, and waiters. We will also introduce new features in the upcoming Version 3 of the SDK, including asynchronous requests, paginators, and the new JMESPath result querying syntax.

Published in: Technology

(DEV305) Building Apps with the AWS SDK for PHP | AWS re:Invent 2014

  1. 1. November 12, 2014 | Las Vegas, NV Jeremy Lindblom (@jeremeamia), AWS Developer Resources @awsforphp
  2. 2. 1.Introduce the SDK (including Version 3) 2.Build an app with the SDK 3.Demonstrate advanced SDK features
  3. 3. $ec2 = ::factory 'region' => 'us-east-1' 'version' => '2014-06-15' $ec2->runInstances 'ImageId' => 'ami-6a6dcc02' 'MinCount' => 'MaxCount' => 'InstanceType' => 'm1.small'
  4. 4. (semver.org)
  5. 5. (cont.)
  6. 6. $ec2=::factory 'region' =>'us-east-1' $ec2->runInstances 'ImageId'=>'ami-6a6dcc02' 'MinCount' => 'MaxCount'=> 'InstanceType' =>'m1.small'
  7. 7. $ec2=::factory 'region' =>'us-east-1' $ec2->runInstances 'ImageId'=>'ami-6a6dcc02' 'MinCount' => 'MaxCount'=> 'InstanceType' =>'m1.small' 'version' =>'2014-06-15'
  8. 8. •Asyncrequests with FutureResultobjects and a Promise API •Support for custom HTTP adapters –cURLno longer required (still the default) –Possible to implement with non-blocking event loops •Result "Paginators" for iterating paginated data •JMESPathquerying of result data •"debug" client option for easy debugging
  9. 9. PHPPHP #nofilter #selphpie #instagood
  10. 10. PHPPHP
  11. 11. (Storage of selPHPies) (Storage of URLs/captions) PHPPHP
  12. 12. "require": { "aws/aws-sdk-php": "~3.0@dev", "silex/silex": "~1.2", "twig/twig": "~1.16", } getcomposer.org
  13. 13. •Instance profile credentials •Credentials file •Environment variables •Hard coding
  14. 14. •Instance profile credentials •Credentials file •Environment variables •Client configuration
  15. 15. •Instance profile credentials •Credentials file •Environment variables •Client configuration FYI: Also supported by the AWS CLI and other SDKs.
  16. 16. •Instance profile credentials •Credentials file •Environment variables •Client configuration
  17. 17. •Instance profile credentials •Credentials file •Environment variables •Client Configuration (BEWARE) 'credentials' => 'key' =>$yourAccessKeyId 'secret' =>$yourSecretAccessKey
  18. 18. phpbin/setup.phpS3 bucketDynamoDBtable Amazon S3 Amazon DynamoDB
  19. 19. $s3->createBucket'Bucket' =>$bucket $s3->waitUntil'BucketExists''Bucket' =>$bucket $dynamoDb->createTable(['TableName'=>$table... $dynamoDb->waitUntil'TableExists' 'TableName'=> $table echo "Done.n"
  20. 20. $result =$dynamoDb->createTable([ 'TableName' =>$table, '@future' => true, ]); // Do other things... // Blocks once dereferenced. $result['TableDescription']['TableStatus'];
  21. 21. $waiter =$dynamoDb->getWaiter( 'TableExists', [...] ); $waiter->wait(); // THIS IS THE SAME AS: $dynamoDb->waitUntil'TableExists'...
  22. 22. $result =$client->operation([...]); $result->then( $onFulfilled, $onRejected, $onProgress, ); // See the React/Promise library
  23. 23. $dynamoDb->createTable([ 'TableName' =>$table, '@future' => true, ])->then(function($result)use ($dynamoDb,$table) { return$dynamoDb->getWaiter('TableExists', [ 'TableName'=>$table, ])->promise(); })->then(function($result) { echo"Done.n"; });
  24. 24. $dynamoDb->createTable([…]) ->then(...) ->then(...); $s3->createBucket([…]) ->then(...) ->then(...);
  25. 25. $app =new $app'aws'=function returnnew 'region' => 'us-east-1' 'version' => 'latest' // ROUTES AND OTHER APPLICATION LOGIC $app->run
  26. 26. $app->get'/'function...
  27. 27. $dynamoDb=$app'aws'->getDynamoDb $result =$dynamoDb->query 'TableName' => 'selphpies' 'Limit' => // ... $items =$result'Items'
  28. 28. $results =$dynamoDb->getPaginator'Query' 'TableName' => 'selphpies' // ... $items =$results->search'Items[]'
  29. 29. $results =$s3->getPaginator'ListObjects'... $files =$results->search'Contents[].Key'
  30. 30. # With Paginators $results =$s3->getPaginator'ListObjects' 'Bucket' =>'my-bucket' $keys =$results->search'Contents[].Key' foreach$keys as$key echo$object'Key'."n" # Without Paginators $marker= do $args='Bucket' =>'my-bucket' if$marker $args'Marker'=$marker $result =$s3->listObjects$args $objects =array$result'Contents' foreach$objects as$object echo$object'Key'."n" $marker $result->search 'NextMarker|| Contents[-1].Key'while$result'IsTruncated'
  31. 31. http://jmespath.org/ $result->search'<JMESPathExpression>' > 'Contents[].Key' > '[CommonPrefixes[].Prefix, Contents[].Key][]' > 'NextMarker|| Contents[-1].Key'
  32. 32. $app->get'/upload'function...
  33. 33. POST $app->post'/upload'function...
  34. 34. try { $caption = $request->request->get('selphpieCaption', '...'); $file = $request->files->get('selphpieImage'); if (!$file instanceofUploadedFile|| $file->getError()) { throw new RuntimeException('...'); } #1. UPLOAD THE IMAGE TO S3 #2. SAVE THE IMAGE DATA TO DYNAMODB $app['session']->getFlashBag()->add('alerts', 'success'); return $app->redirect('/'); } catch (Exception $e) { $app['session']->getFlashBag()->add('alerts', 'danger'); return $app->redirect('/upload'); }
  35. 35. $s3 =$app['aws']->getS3(); $result =$s3->putObject([ 'Bucket' => 'selphpies', 'Key' => $file->getClientOriginalName(), 'Body' =>fopen($file->getFileName(), 'r'), 'ACL' => 'public-read', ]);
  36. 36. // Automatically switches to multipart uploads // if the file is larger than default threshold. $result=$s3->upload( 'selphpies', $file->getClientOriginalName(), fopen($file->getPathname(), 'r'), 'public-read' );
  37. 37. $dynamoDb->putItem([ 'TableName' =>'selphpies', 'Item'=>[ // ... 'src'=>['S' =>$result['ObjectURL']], 'caption'=>['S' =>$caption], ], ]);
  38. 38. PHP such php so cloud wow very selfie much app #phpdoge
  39. 39. PHP
  40. 40. Really
  41. 41. PHP
  42. 42. PHP
  43. 43. PHP
  44. 44. PHP Step 1 Step 2 Step 3 Step 4
  45. 45. Step 1
  46. 46. $results=$dynamoDb->getPaginator'Scan' 'TableName' =>$oldTable 'KeyConditions' =>
  47. 47. Step 2
  48. 48. $records =new$dynamoDb 'table' =>$newTable // $records->put($selphpie); $records->flush
  49. 49. Step 3
  50. 50. $commands = $commands=$s3->getCommand'CopyObject'... $commands=$s3->getCommand'CopyObject'... $commands=$s3->getCommand'CopyObject'... // ... $s3->executeAll$commands
  51. 51. $getCopyCommands= function$resultsuse... foreach$results->search'Items[]'as$selphpie $command =$s3->getCommand'CopyObject' 'Bucket' =>$newBucket 'Key' => $key 'SourceFile' =>"{$oldBucket}/{$key}" // ... (Attach event listener in Step 4) ... yield$command $s3->executeAll$getCopyCommands$results
  52. 52. Step 4
  53. 53. $emitter =$command->getEmitter $emitter->on'process'function$eventuse... if$result =$event->getResult $selphpie'url''S'=$result'ObjectURL' // Add new record to WriteRequestBatch $records->put$selphpieelse // Log/handle error...
  54. 54. PHP Step 1 Step 2 Step 3 Step 4
  55. 55. PHP $results = $dynamoDb->getPaginator('Scan', [ 'TableName' => $oldBucket, 'KeyConditions' => [ 'app' => [ 'AttributeValueList' => [['S' => $oldAppKey]], 'ComparisonOperator' => 'EQ', ], ], ]); $records = new WriteRequestBatch($dynamoDb, [ 'table' => $newTable ]); $getCopyCommands= function ($results) use ( $s3, $records, $oldBucket, $newBucket, $newAppKey ) { foreach($results->search('Items[]') as $selphpie) { $key = Url::fromString($selphpie['url']['S'])->getPath(); $command = $s3->getCommand('CopyObject', [ 'Bucket' => $newBucket, 'Key' => $key, 'SourceFile' => "{$oldBucket}/{$key}", ]); $emitter = $command->getEmitter(); $emitter->on('process', function ($event) use ( $selphpie, $records, $newAppKey ) { if ($result = $event->getResult()) { $selphpie['url']['S'] = $result['ObjectURL']; $selphpie['app']['S'] = $newAppKey; // Add new record to WriteRequestBatch $records->put($selphpie); } else { // Log/handle error... } }); yield $command; } }; $s3->executeAll($getCopyCommands($results)); $records->flush();
  56. 56. @awsforphpgithub.com/aws/aws-sdk-php/releasesblogs.aws.amazon.com/php
  57. 57. github.com/aws/aws-sdk-phpforums.aws.amazon.com
  58. 58. http://bit.ly/awsevals @awsforphp Come find us at the AWS booths if you have questions. Your Homework:

×