Question

I'm using the rackspace cloudfiles API to upload files on the fly and the first thing it needs to do is check whether the container exists and if not, create it.

So I write the following:

if($container = $conn->get_container('my_container')){
   echo 'yay';

} else {
   $container = $conn->create_container('my_container');
   $container->make_public();   
}                                           

But if the container doesn't exist get_container throws an exception and so I get a fatal error. What's the best way to do what I'm trying to do here?

Was it helpful?

Solution

try {
    $container = $conn->get_container('my_container');
    $obj_list = $container->list_objects();
    print_r($obj_list);
}
catch (Exception $e) {
    $container = $conn->create_container('my_container');
    //$container->make_public();
}

OTHER TIPS

you could expect an explicit exception also:

try {
    $container = $conn->get_container('my_container');
    $obj_list = $container->list_objects();
    print_r($obj_list);
}
catch (NoSuchContainerException $e) {
    $container = $conn->create_container('my_container');
}

this will not fail if you have networking problems or something related.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top