If you're asking, "What's Yii?" check out my earlier tutorial, Introduction to the Yii Framework, which reviews the benefits of Yii and includes an overview of what's new in Yii 2.0, released in October 2014.
In this Programming With Yii2 series, I'm guiding readers in use of the Yii2 Framework for PHP. In today's tutorial, I'll walk you through the basics of browsing, uploading and downloading files to and from Amazon's cloud-based S3 storage service. Essentially, I've created a simple storage model and controller as examples which you can extend for your needs.
Just a reminder, I do participate in the comment threads below. I'm especially interested if you have different approaches, additional ideas, or want to suggest topics for future tutorials. If you have a question or topic suggestion, please post below. You can also reach me on Twitter @reifman directly.
What's Amazon S3?
Amazon S3 provides easy-to-use, advanced cloud-based storage for objects and files. It offers 99.99% availability and 99.999999999% durability of objects.
It offers a variety of features for simple or advanced usage. It's commonly used as the storage component for Amazon's CDN service CloudFront, but these are distinct and can be used independently of each other.
You can also use S3 to migrate files over time to archive in Amazon Glacier, for added cost savings.
Like most all of AWS, you operate S3 via APIs, and today, I'm going to walk you through browsing, uploading and downloading files from S3 with Yii.
Getting Started
To run the demonstration code, you'll need your own Amazon AWS account and access keys. You can browse your S3 tree from the AWS console shown below:
S3 consists of buckets which hold numerous directories and files within them. Since I used to use AWS as a CDN, my WordPress tree remains in my old bucket. You can browse your bucket as well:
As I traverse the tree of objects, here's a deeper view of my bucket contents:
Programming With S3
Again, I'll build on the hello tree from GitHub for our demonstration code (see the link on this page.) It's derived from Yii2 basic.
Obtaining Your Access Keys
You will need access keys for the AWS S3 API if you don't already have them. If not, you can get them by browsing to Security Credentials and creating a new pair:
For our code demonstration, you'll need to place them in your hello.ini file with other secure keys and codes:
$ more /var/secure/hello.ini mysql_host="localhost" mysql_db="hello" mysql_un="tom_mcfarlin" mysql_pwd="is-never-gonna-give-up-rick-astley" aws_s3_access = "AXXXXXXXXXXXXXXXXXXXXXXXXXXXA" aws_s3_secret = "nXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXb" aws_s3_region = "us-east-1"
Installing the Yii Extension for AWS
For this tutorial, we'll use Federico Motta's AWS extension for Yii2. He's definitely the youngest Yii programmer whose code I've used for an Envato Tuts+ tutorial:
Isn't it amazing how quickly kids are picking up programming these days?
Here's the installation process using composer:
$ composer require fedemotta/yii2-aws-sdk Using version ^2.0 for fedemotta/yii2-aws-sdk ./composer.json has been updated Loading composer repositories with package information Updating dependencies (including require-dev) ... - Installing aws/aws-sdk-php (3.18.27) Downloading: 100% - Installing fedemotta/yii2-aws-sdk (v2.0) Loading from cache aws/aws-sdk-php suggests installing aws/aws-php-sns-message-validator (To validate incoming SNS notifications) aws/aws-sdk-php suggests installing doctrine/cache (To use the DoctrineCacheAdapter) Writing lock file Generating autoload files
Afterwards, I also installed the two libraries it suggests, but did not install all of the next level of suggestions for my local development machine:
$ composer require aws/aws-php-sns-message-validator Using version ^1.1 for aws/aws-php-sns-message-validator ./composer.json has been updated Loading composer repositories with package information Updating dependencies (including require-dev) - Installing aws/aws-php-sns-message-validator (1.1.0) Loading from cache Writing lock file Generating autoload files $ composer require cache/doctrine-adapter Using version ^0.5.0 for cache/doctrine-adapter ./composer.json has been updated Loading composer repositories with package information Updating dependencies (including require-dev) - Installing doctrine/cache (v1.6.0) Loading from cache - Installing psr/cache (1.0.0) Loading from cache - Installing cache/taggable-cache (0.4.0) Loading from cache - Installing psr/log (1.0.0) Loading from cache - Installing cache/adapter-common (0.3.2) Loading from cache - Installing cache/doctrine-adapter (0.5.0) Loading from cache cache/doctrine-adapter suggests installing ext-apc (Allows for caching with Apc) cache/doctrine-adapter suggests installing ext-memcache (Allows for caching with Memcache) cache/doctrine-adapter suggests installing ext-memcached (Allows for caching with Memcached) cache/doctrine-adapter suggests installing ext-redis (Allows for caching with Redis) Writing lock file Generating autoload files
I also registered the awssdk
component within hello/config/web.php:
'components' => [ 'awssdk' => [ 'class' => 'fedemotta\awssdk\AwsSdk', 'credentials' => [ //you can use a different method to grant access 'key' => $config['aws_s3_access'], 'secret' => $config['aws_s3_secret'], ], 'region' => $config['aws_s3_region'], //i.e.: 'us-east-1' 'version' => 'latest', //i.e.: 'latest' ],
Browsing My S3 Directories
For today's demonstration, I created a hello/controllers/StorageController.php with action methods to run each example, such as http://localhost:8888/hello/storage/browse to browse directories.
These methods in turn call the Storage.php model I created with their own methods.
Here's the controller code:
public function actionBrowse() { $s = new Storage(); $s->browse('jeff-reifman-wp',"manual"); }
It requests that the Storage model reach up to the clouds in the "S3ky" and browse the manual directory.
Each time the Storage.php model is instantiated, it loads the AWS SDK extension and creates an S3 instance:
<?php namespace app\models; use Yii; use yii\base\Model; class Storage extends Model { private $aws; private $s3; function __construct() { $this->aws = Yii::$app->awssdk->getAwsSdk(); $this->s3 = $this->aws->createS3(); }
In my browse example, I'm just echoing the directories and files, but you can feel free to customize this code as you need:
public function browse($bucket='',$prefix='') { $result = $this->s3->listObjects(['Bucket' => $bucket,"Prefix" => $prefix])->toArray(); foreach ($result as $r) { if (is_array($r)) { if (array_key_exists('statusCode',$r)) { echo 'Effective URL: '.$r['effectiveUri'].'<br />'; } else { foreach ($r as $item) { echo $item['Key'].'<br />'; } } } else { echo $r.'<br />'; } } }
Here are the results when I browse to http://localhost:8888/hello/storage/browse:
Uploading Files
To upload a file, you need to specify the local path and the remote destination key. Here's the controller code for upload:
public function actionUpload() { $bucket = 'jeff-reifman-wp'; $keyname = '/manual/upload.txt'; $filepath ='/Users/Jeff/Sites/hello/upload.txt'; $s = new Storage(); $result = $s->upload($bucket,$keyname,$filepath); echo $result['ObjectURL']; }
And here is the Storage model method:
public function upload($bucket,$keyname,$filepath) { $result = $this->s3->putObject(array( 'Bucket' => $bucket, 'Key' => $keyname, 'SourceFile' => $filepath, 'ContentType' => 'text/plain', 'ACL' => 'public-read', 'StorageClass' => 'REDUCED_REDUNDANCY', 'Metadata' => array( 'param1' => 'value 1', 'param2' => 'value 2' ) )); return $result;
Browsing to http://localhost:8888/hello/storage/upload displays the returning URL from which I can view the uploaded file, because I specified public-read
in my code above:
In turn, browsing to the S3 address above shows the contents of the uploaded file:
This is a test to upload to S3
Downloading Files
Here's the controller code for downloading a file:
public function actionDownload() { $s = new Storage(); $f = $s->download('jeff-reifman-wp','files/2013/01/i103-wedding-cover.jpg'); //download the file header('Content-Type: ' . $f['ContentType']); echo $f['Body']; }
Since the browser responds to the content-type, it should display the appropriate image, which I'm requesting here.
Note: I'm downloading a cover image from my experience marrying a corporation named Corporate Person to a woman (yes, it actually happened). The marriage didn't work out long term.
Here's the Storage model code for downloading:
public function download($bucket='',$key ='') { //get the last object from s3 //$object = end($result['Contents']); // $key = $object['Key']; $file = $this->s3->getObject([ 'Bucket' => $bucket, 'Key' => $key, ]); return $file; // save it to disk }
Here's what you see when the file is streamed to the browser—that's the bride celebrating by waving the actual marriage license to Corporate Person (I'm smiling in the background, mission accomplished).
Certainly, you could just as easily store the results on your server in a file. It's up to you. I encourage you to play with the code and customize it as you need.
What's Next?
I hope this helps you with the basics of using AWS S3 from your Yii application.
If you like the concept of cloud-based object and file storage but want to find other providers, check out Alternatives to Amazon AWS. I've been gradually moving away from AWS for a number of reasons mentioned in the article. One of my next tasks is to migrate my S3 objects that are still partly in use to my own server, which I can mirror with KeyCDN.
Watch for upcoming tutorials in our Programming With Yii2 series as we continue diving into different aspects of the framework. You may also want to check out our Building Your Startup With PHP series which is using Yii2's advanced template as we build a real-world application. The Meeting Planner application in the startup series is now ready for use, and it's all built in Yii.
If you'd like to know when the next Yii2 tutorial arrives, follow me @reifman on Twitter or check my instructor page.
Comments