Registering Amazon S3 Stream Wrapper in Zend Framework
Amazon’s S3 (Simple Storage Service) is an unlimited, reliable, and affordable storage solution for storing any type and amount of data. Some example uses are:
* User uploaded photos and documents
* Video
* Backups
* Log file storage
* Any other large amount of data that can be burdensome to store locally
Amazon S3 can provide peace of mind and significant cost savings to organizations of all sizes. But how do you get your data in and out? The easiest way is probably by registering a stream wrapper. A stream wrapper is simply a way for your code to interact with various sources of data (streams), handling all the technical details of reading and writing for you.
Of course, to use Amazon’s S3, you’ll need an account. Head over to aws.amazon.com and get signed up, and bring back your Access Key and Secret Access Key.
Let’s see some code:
$s3 = new Zend_Service_Amazon_S3($awsKey, $awsSecretKey); $s3->registerStreamWrapper();
And that’s it! Now to use S3, you can use PHP’s file functions you’re already used to, such as file(), file_put_contents(), file_get_contents(), mkdir(), and many others, in the following way:
$contents = file_get_contents('s3://mybucket/myfilename.txt');
$size = filesize('s3://mybucket/myfilename.txt');
//Create new BUCKET (not directory)
mkdir('s3://mynewbucket');
Note the use of the ‘s3://’ prefix…This tells PHP to use the S3 stream wrapper we just registered, instead of accessing the files normally.
Nearly all of PHP’s file and directory functions will operate seamlessly with the S3 wrapper.
NOTE: all directory functions such as mkdir and is_dir operate on buckets rather than actual directories. In S3, you have buckets and files…not directories. You can mimic directory structure by naming your files such as ‘/pseudofolder/myfile.txt’, though.
The most useful way to use S3 is to stick the above code into an early running plugin or resource (on Zend MVC applications) and then save the $s3 object into the registry for application wide use.
Good luck and have fun!