PhpRiot
Download Article
Download this article or the entire “Zend Framework 101” series with all listings and files.

Includes 2 bonus listings!




More information
Related Books
Zend Framework 1.8 Web Application Development

Zend Framework 1.8 Web Application Development

Design, develop, and deploy feature-rich PHP web applications with this MVC framework...

Pro Zend Framework Techniques: Build a Full CMS Project (Expert's Voice)

Pro Zend Framework Techniques: Build a Full CMS Project (Expert's Voice)

The Zend Framework is a truly amazing PHP–based web application development framework and...
PhpRiot Newsletter
Your Email Address:

More information

Zend Framework 101: Zend_Service_Amazon_S3

Create a Bucket

Buckets are created using the createBucket() method. This method accepts the name of the bucket as its first argument. If the bucket is successfully created, this method returns true. If the name of the bucket is not valid, an exception is thrown.

If the bucket cannot be created (likely due to somebody else owning that bucket name), false is returned from createBucket().

It is important to note that if you have already created a bucket then try to create it again, true will still be returned. If you want to ensure that a new bucket is being creating you should first retrieve a list of buckets and check for the name.

The following listing demonstrates creating a bucket.

Listing 4 Creating a new bucket (create-bucket.php)
<?php
    require_once('Zend/Service/Amazon/S3.php');
 
    $awsKey       = '[your key]';
    $awsSecretKey = '[your secret key]';
 
    $s3 = new Zend_Service_Amazon_S3($awsKey, $awsSecretKey);
 
    $bucketName = 'phpriot-test-bucket';
 
    try {
        $buckets    = $s3->getBuckets();
 
        if (in_array($bucketName, $buckets)) {
            throw new Exception('You already have this bucket');
        }
 
        $succ = $s3->createBucket($bucketName);
 
        if ($succ) {
            echo "Bucket created!";
        }
        else {
            echo "Unable to create bucket!";
        }
    }
    catch (Exception $ex) {
        echo $ex->getMessage();
    }
?>

This code begins by specifying the name of the bucket to create in $bucketName. It then retrieves a list of buckets and checks that you don't already have that bucket. If so, it throws an exception which is then handled at the bottom of the script.

Next it tries to create the bucket. If the name is invalid an exception is thrown. Otherwise, the call to createBucket() returns a boolean.

In This Article



Bonus listings: 2 available