HPCloud-PHP  1.2.0
PHP bindings for HPCloud and OpenStack services.
 All Classes Namespaces Files Functions Variables Pages
Container Class Reference

A container in an ObjectStorage. More...

Public Member Functions

 __construct ($name, $url=NULL, $token=NULL)
 Construct a new Container.
 useCDN ($url, $sslUrl)
 Set the URL of the CDN to use.
 name ()
 Get the name of this container.
 bytes ()
 Get the number of bytes in this container.
 metadata ()
 Get the container metadata.
 setMetadata ($metadata)
 Set the tags on the container.
 count ()
 Get the number of items in this container.
 save (Object $obj, $file=NULL)
 Save an Object into Object Storage.
 updateMetadata (Object $obj)
 Update an object's metadata.
 copy (Object $obj, $newName, $container=NULL)
 Copy an object to another place in object storage.
 object ($name, $requireSSL=TRUE)
 Get the object with the given name.
 proxyObject ($name)
 Fetch an object, but delay fetching its contents.
 remoteObject ($name)
 This has been replaced with proxyObject().
 objects ($limit=NULL, $marker=NULL)
 Get a list of objects in this container.
 objectsWithPrefix ($prefix, $delimiter= '/', $limit=NULL, $marker=NULL)
 Retrieve a list of Objects with the given prefix.
 objectsByPath ($path, $delimiter= '/', $limit=NULL, $marker=NULL)
 Specify a path (subdirectory) to traverse.
 url ()
 Get the URL to this container.
 cdnUrl ($ssl=TRUE)
 acl ()
 Get the ACL.
 getIterator ()
 Return the iterator of contents.
 delete ($name)
 Remove the named object from storage.

Static Public Member Functions

static generateMetadataHeaders (array $metadata, $prefix=NULL)
 Transform a metadata array into headers.
static objectUrl ($base, $oname)
 Create an object URL.
static extractHeaderAttributes ($headers, $prefix=NULL)
 Extract object attributes from HTTP headers.
static newFromJSON ($jsonArray, $token, $url)
 Create a new Container from JSON data.
static newFromResponse ($name, $response, $token, $url)
 Given an OpenStack HTTP response, build a Container.

Public Attributes

const METADATA_HEADER_PREFIX = 'X-Object-Meta-'
 The prefix for any piece of metadata passed in HTTP headers.
const CONTAINER_METADATA_HEADER_PREFIX = 'X-Container-Meta-'

Protected Member Functions

 loadExtraData ()
 Get missing fields.
 objectQuery ($params=array(), $limit=NULL, $marker=NULL)
 Perform the HTTP query for a list of objects and de-serialize the results.

Protected Attributes

 $name = NULL
 $count = NULL
 $bytes = NULL
 $token
 $url
 $baseUrl
 $acl
 $metadata
 $cdnUrl
 $cdnSslUrl

Detailed Description

A container in an ObjectStorage.

An Object Storage instance is divided into containers, where each container can hold an arbitrary number of objects. This class describes a container, providing access to its properties and to the objects stored inside of it.

Containers are iterable, which means you can iterate over a container and access each file inside of it.

Typically, containers are created using ObjectStorage::createContainer(). They are retrieved using ObjectStorage::container() or ObjectStorage::containers().

<?php
use \HPCloud\Storage\ObjectStorage;
use \HPCloud\Storage\ObjectStorage\Container;
use \HPCloud\Storage\ObjectStorage\Object;
// Create a new ObjectStorage instance, logging in with older Swift
// credentials.
$store = ObjectStorage::newFromSwiftAuth('user', 'key', 'http://example.com');
// Get the container called 'foo'.
$container = $store->container('foo');
// Create an object.
$obj = new Object('bar.txt');
$obj->setContent('Example content.', 'text/plain');
// Save the new object in the container.
$container->save($obj);
?>

Once you have a Container, you manipulate objects inside of the container.

Todo:

Add support for container metadata.

Add CDN support fo container listings.

Definition at line 74 of file Container.php.

Constructor & Destructor Documentation

__construct (   $name,
  $url = NULL,
  $token = NULL 
)

Construct a new Container.

Attention
Typically a container should be created by ObjectStorage::createContainer(). Get existing containers with ObjectStorage::container() or ObjectStorage::containers(). Using the constructor directly has some side effects of which you should be aware.

Simply creating a container does not save the container remotely.

Also, this does no checking of the underlying container. That is, simply constructing a Container in no way guarantees that such a container exists on the origin object store.

The constructor involves a selective lazy loading. If a new container is created, and one of its accessors is called before the accessed values are initialized, then this will make a network round-trip to get the container from the remote server.

Containers loaded from ObjectStorage::container() or Container::newFromRemote() will have all of the necessary values set, and thus will not require an extra network transaction to fetch properties.

The practical result of this:

  • If you are creating a new container, it is best to do so with ObjectStorage::createContainer().
  • If you are manipulating an existing container, it is best to load the container with ObjectStorage::container().
  • If you are simply using the container to fetch resources from the container, you may wish to use new Container($name, $url, $token) and then load objects from that container. Note, however, that manipulating the container directly will likely involve an extra HTTP transaction to load the container data.
  • When in doubt, use the ObjectStorage methods. That is always the safer option.
Parameters
string$nameThe name.
string$urlThe full URL to the container.
string$tokenThe auth token.

Definition at line 328 of file Container.php.

References $name, ObjectStorage\$token, ObjectStorage\$url, Container\name(), ObjectStorage\token(), and ObjectStorage\url().

Member Function Documentation

acl ( )

Get the ACL.

Currently, if the ACL wasn't added during object construction, calling acl() will trigger a request to the remote server to fetch the ACL. Since only some Swift calls return ACL data, this is an unavoidable artifact.

Calling this on a Container that has not been stored on the remote ObjectStorage will produce an error. However, this should not be an issue, since containers should always come from one of the ObjectStorage methods.

Todo:
Determine how to get the ACL from JSON data.
Return values
\HPCloud\Storage\ObjectStorage\ACL
Returns
HPCloud::Storage::ObjectStorage::ACL An ACL, or NULL if the ACL could not be retrieved.

Definition at line 1006 of file Container.php.

References Container\acl(), and Container\loadExtraData().

Referenced by Container\acl(), and Container\loadExtraData().

bytes ( )

Get the number of bytes in this container.

Return values
int
Returns
int The number of bytes in this container.

Definition at line 373 of file Container.php.

References Container\bytes(), and Container\loadExtraData().

Referenced by Container\bytes(), and Container\loadExtraData().

cdnUrl (   $ssl = TRUE)

Definition at line 984 of file Container.php.

copy ( Object  $obj,
  $newName,
  $container = NULL 
)

Copy an object to another place in object storage.

An object can be copied within a container. Essentially, this will give you duplicates of the file, each with a new name.

An object can be copied to another container if the name of the other container is specified, and if that container already exists.

Note that there is no MOVE operation. You must copy and then DELETE in order to achieve that.

Parameters
object$objHPCloud::Storage::ObjectStorage::Object The object to copy. This object MUST already be saved on the remote server. The body of the object is not sent. Instead, the copy operation is performed on the remote server. You can, and probably should, use a RemoteObject here.
string$newNameThe new name of this object. If you are copying across containers, the name can be the same. If you are copying within the same container, though, you will need to supply a new name.
string$containerThe name of the alternate container. If this is set, the object will be saved into this container. If this is not sent, the copy will be performed inside of the original container.

Definition at line 654 of file Container.php.

References $container, $name, Object\name(), ObjectStorage\token(), and ObjectStorage\url().

count ( )

Get the number of items in this container.

Since Container implements Countable, the PHP builtin count() can be used on a Container instance:

<?php
count($container) === $container->count();
?>
Return values
int
Returns
int The number of items in this container.

Definition at line 453 of file Container.php.

References Container\count(), and Container\loadExtraData().

Referenced by Container\count(), and Container\loadExtraData().

delete (   $name)

Remove the named object from storage.

Parameters
string$nameThe name of the object to remove.
Return values
boolean
Returns
boolean TRUE if the file was deleted, FALSE if no such file is found.

Definition at line 1147 of file Container.php.

References $name, ObjectStorage\$url, ObjectStorage\token(), and ObjectStorage\url().

static extractHeaderAttributes (   $headers,
  $prefix = NULL 
)
static

Extract object attributes from HTTP headers.

When OpenStack sends object attributes, it sometimes embeds them in HTTP headers with a prefix. This function parses the headers and returns the attributes as name/value pairs.

Note that no decoding (other than the minimum amount necessary) is done to the attribute names or values. The Open Stack Swift documentation does not prescribe encoding standards for name or value data, so it is left up to implementors to choose their own strategy.

Parameters
array$headersAn associative array of HTTP headers.
string$prefixThe prefix on metadata headers.
Return values
array
Returns
array An associative array of name/value attribute pairs.

Definition at line 187 of file Container.php.

References $key, and Container\METADATA_HEADER_PREFIX.

Referenced by RemoteObject\extractFromHeaders(), Container\loadExtraData(), RemoteObject\newFromHeaders(), and Container\newFromResponse().

static generateMetadataHeaders ( array  $metadata,
  $prefix = NULL 
)
static

Transform a metadata array into headers.

This is used when storing an object in a container.

Parameters
array$metadataAn associative array of metadata. Metadata is not escaped in any way (there is no codified spec by which to escape), so make sure that keys are alphanumeric (dashes allowed) and values are ASCII-armored with no newlines.
string$prefixA prefix for the metadata headers.
Return values
array
Returns
array An array of headers.
See Also
http://docs.openstack.org/bexar/openstack-object-storage/developer/content/ch03s03.html#d5e635
http://docs.openstack.org/bexar/openstack-object-storage/developer/content/ch03s03.html#d5e700

Definition at line 118 of file Container.php.

References $key, and Container\METADATA_HEADER_PREFIX.

Referenced by ObjectStorage\createContainer().

getIterator ( )

Return the iterator of contents.

A Container is Iterable. This means that you can use a container in a foreach loop directly:

<?php
foreach ($container as $object) {
print $object->name();
}
?>

The above is equivalent to doing the following:

<?php
$objects = $container->objects();
foreach ($objects as $object) {
print $object->name();
}
?>

Note that there is no way to pass any constraints into an iterator. You cannot limit the number of items, set an marker, or add a prefix.

Definition at line 1134 of file Container.php.

References Container\objects().

loadExtraData ( )
protected

Get missing fields.

Not all containers come fully instantiated. This method is sometimes called to "fill in" missing fields.

Return values
HPCloud::Storage::ObjectStorage::Comtainer
Returns

Definition at line 1022 of file Container.php.

References Container\acl(), Container\bytes(), Container\CONTAINER_METADATA_HEADER_PREFIX, Container\count(), Container\extractHeaderAttributes(), ACL\newFromHeaders(), Container\setMetadata(), ObjectStorage\token(), and ObjectStorage\url().

Referenced by Container\acl(), Container\bytes(), Container\count(), and Container\metadata().

metadata ( )

Get the container metadata.

Metadata (also called tags) are name/value pairs that can be attached to a container.

Names can be no longer than 128 characters, and values can be no more than 256. UTF-8 or ASCII characters are allowed, though ASCII seems to be preferred.

If the container was loaded from a container listing, the metadata will be fetched in a new HTTP request. This is because container listings do not supply the metadata, while loading a container directly does.

Return values
array
Returns
array An array of metadata name/value pairs.

Definition at line 399 of file Container.php.

References Container\loadExtraData(), and Container\metadata().

Referenced by Container\metadata(), and Container\setMetadata().

name ( )

Get the name of this container.

Return values
string
Returns
string The name of the container.

Definition at line 362 of file Container.php.

References $name.

Referenced by Container\__construct().

static newFromJSON (   $jsonArray,
  $token,
  $url 
)
static

Create a new Container from JSON data.

This is used in lieue of a standard constructor when fetching containers from ObjectStorage.

Parameters
array$jsonArrayAn associative array as returned by json_decode($foo, TRUE);
string$tokenThe auth token.
string$urlThe base URL. The container name is automatically appended to this at construction time.
Return values
HPCloud::Storage::ObjectStorage::Comtainer
Returns
A new container object.

Definition at line 222 of file Container.php.

References $container, ObjectStorage\$token, and ObjectStorage\$url.

Referenced by ObjectStorage\containers().

static newFromResponse (   $name,
  $response,
  $token,
  $url 
)
static

Given an OpenStack HTTP response, build a Container.

This factory is intended for use by low-level libraries. In most cases, the standard constructor is preferred for client-size Container initialization.

Parameters
string$nameThe name of the container.
object$responseHPCloud::Transport::Response The HTTP response object from the Transporter layer
string$tokenThe auth token.
string$urlThe base URL. The container name is automatically appended to this at construction time.
Return values
HPCloud::Storage::ObjectStorage::Container
Returns
The Container object, initialized and ready for use.

Definition at line 266 of file Container.php.

References $container, Container\$metadata, $name, ObjectStorage\$token, ObjectStorage\$url, Container\CONTAINER_METADATA_HEADER_PREFIX, Container\extractHeaderAttributes(), and ACL\newFromHeaders().

Referenced by ObjectStorage\container().

object (   $name,
  $requireSSL = TRUE 
)

Get the object with the given name.

This fetches a single object with the given name. It downloads the entire object at once. This is useful if the object is small (under a few megabytes) and the content of the object will be used. For example, this is the right operation for accessing a text file whose contents will be processed.

For larger files or files whose content may never be accessed, use remoteObject(), which delays loading the content until one of its content methods (e.g. RemoteObject::content()) is called.

This does not yet support the following features of Swift:

  • Byte range queries.
  • If-Modified-Since/If-Unmodified-Since
  • If-Match/If-None-Match

If a CDN has been specified either using useCDN() or ObjectStorage::useCDN(), this will attempt to fetch the object from the CDN.

Parameters
string$nameThe name of the object to load.
boolean$requireSSLIf this is TRUE (the default), then SSL will always be used. If this is FALSE, then CDN-based fetching will use non-SSL, which is faster.
Return values
HPCloud::Storage::ObjectStorage::RemoteObject
Returns
A remote object with the content already stored locally.

Definition at line 716 of file Container.php.

References $name, ObjectStorage\$token, ObjectStorage\$url, ObjectStorage\cdnUrl(), and ObjectStorage\url().

objectQuery (   $params = array(),
  $limit = NULL,
  $marker = NULL 
)
protected

Perform the HTTP query for a list of objects and de-serialize the results.

Definition at line 1056 of file Container.php.

References ObjectStorage\$url, ObjectStorage\token(), and ObjectStorage\url().

Referenced by Container\objects(), Container\objectsByPath(), and Container\objectsWithPrefix().

objects (   $limit = NULL,
  $marker = NULL 
)

Get a list of objects in this container.

This will return a list of objects in the container. With no parameters, it will attempt to return a listing of all objects in the container. However, by setting contraints, you can retrieve only a specific subset of objects.

Note that OpenStacks Swift will return no more than 10,000 objects per request. When dealing with large datasets, you are encouraged to use paging.

Paging

Paging is done with a combination of a limit and a marker. The limit is an integer indicating the maximum number of items to return. The marker is the string name of an object. Typically, this is the last object in the previously returned set. The next batch will begin with the next item after the marker (assuming the marker is found.)

Parameters
int$limitAn integer indicating the maximum number of items to return. This cannot be greater than the Swift maximum (10k).
string$markerThe name of the object to start with. The query will begin with the next object AFTER this one.
Return values
array
Returns
array List of RemoteObject or Subdir instances.

Definition at line 852 of file Container.php.

References Container\objectQuery().

Referenced by Container\getIterator().

objectsByPath (   $path,
  $delimiter = '/',
  $limit = NULL,
  $marker = NULL 
)

Specify a path (subdirectory) to traverse.

OpenStack Swift provides two basic ways to handle directory-like structures. The first is using a prefix (see objectsWithPrefix()). The second is to create directory markers and use a path.

A directory marker is just a file with a name that is directory-like. You create it exactly as you create any other file. Typically, it is 0 bytes long.

<?php
$dir = new Object('a/b/c', '');
$container->save($dir);
?>

Using objectsByPath() with directory markers will return a list of Object instances, some of which are regular files, and some of which are just empty directory marker files. When creating directory markers, you may wish to set metadata or content-type information indicating that they are directory markers.

At one point, the OpenStack documentation suggested that the path method was legacy. More recent versions of the documentation no longer indicate this.

Parameters
string$pathThe path prefix.
string$delimiterThe character used to delimit names. By default, this is '/'.
int$limitAn integer indicating the maximum number of items to return. This cannot be greater than the Swift maximum (10k).
string$markerThe name of the object to start with. The query will begin with the next object AFTER this one.

Definition at line 961 of file Container.php.

References Container\objectQuery().

objectsWithPrefix (   $prefix,
  $delimiter = '/',
  $limit = NULL,
  $marker = NULL 
)

Retrieve a list of Objects with the given prefix.

Object Storage containers support directory-like organization. To get a list of items inside of a particular "subdirectory", provide the directory name as a "prefix". This will return only objects that begin with that prefix.

(Directory-like behavior is also supported by using "directory markers". See objectsByPath().)

Prefixes

Prefixes are basically substring patterns that are matched against files on the remote object storage.

When a prefix is used, object storage will begin to return not just Object instsances, but also Subdir instances. A Subdir is simply a container for a "path name".

Delimiters

Object Storage (OpenStack Swift) does not have a native concept of files and directories when it comes to paths. Instead, it merely represents them and simulates their behavior under specific circumstances.

The default behavior (when prefixes are used) is to treat the '/' character as a delimiter. Thus, when it encounters a name like this: foo/bar/baz.txt and the prefix is foo/, it will parse return a Subdir called foo/bar.

Similarly, if you store a file called foo:bar:baz.txt and then set the delimiter to : and the prefix to foo:, it will return the Subdir foo:bar. However, merely setting the delimiter back to / will not allow you to query foo/bar and get the contents of foo:bar.

Setting $delimiter will tell the Object Storage server which character to parse the filenames on. This means that if you use delimiters other than '/', you need to be very consistent with your usage or else you may get surprising results.

Parameters
string$prefixThe leading prefix.
string$delimiterThe character used to delimit names. By default, this is '/'.
int$limitAn integer indicating the maximum number of items to return. This cannot be greater than the Swift maximum (10k).
string$markerThe name of the object to start with. The query will begin with the next object AFTER this one.
Return values
array
Returns
array List of RemoteObject or Subdir instances.

Definition at line 914 of file Container.php.

References Container\objectQuery().

static objectUrl (   $base,
  $oname 
)
static

Create an object URL.

Given a base URL and an object name, create an object URL.

This is useful because object names can contain certain characters (namely slashes (/)) that are normally URLencoded when they appear inside of path sequences.

Note
Swift does not distinguish between %2F and a slash character, so this is not strictly necessary.
Parameters
string$baseThe base URL. This is not altered; it is just prepended to the returned string.
string$onameThe name of the object.
Return values
string
Returns
string The URL to the object. Characters that need escaping will be escaped, while slash characters are not. Thus, the URL will look pathy.

Definition at line 151 of file Container.php.

proxyObject (   $name)

Fetch an object, but delay fetching its contents.

This retrieves all of the information about an object except for its contents. Size, hash, metadata, and modification date information are all retrieved and wrapped.

The data comes back as a RemoteObject, which can be used to transparently fetch the object's content, too.

Why Use This?

The regular object() call will fetch an entire object, including its content. This may not be desireable for cases where the object is large.

This method can featch the relevant metadata, but delay fetching the content until it is actually needed.

Since RemoteObject extends Object, all of the calls that can be made to an Object can also be made to a RemoteObject. Be aware, though, that calling RemoteObject::content() will initiate another network operation.

Parameters
string$nameThe name of the object to fetch.
Return values
HPCloud::Storage::ObjectStorage::RemoteObject
Returns
A remote object ready for use.

Definition at line 781 of file Container.php.

References $name, ObjectStorage\$url, ObjectStorage\cdnUrl(), ObjectStorage\token(), and ObjectStorage\url().

Referenced by Container\remoteObject().

remoteObject (   $name)

This has been replaced with proxyObject().

Deprecated:

Definition at line 817 of file Container.php.

References $name, and Container\proxyObject().

save ( Object  $obj,
  $file = NULL 
)

Save an Object into Object Storage.

This takes an HPCloud::Storage::ObjectStorage::Object and stores it in the given container in the present container on the remote object store.

Parameters
object$objHPCloud::Storage::ObjectStorage::Object The object to store.
resource$fileAn optional file argument that, if set, will be treated as the contents of the object.
Return values
boolean
Returns
boolean TRUE if the object was saved.
Exceptions
HPCloud::Transport::LengthRequiredExceptionif the Content-Length could not be determined and chunked encoding was not enabled. This should not occur for this class, which always automatically generates Content-Length headers. However, subclasses could generate this error.
HPCloud::Transport::UnprocessableEntityExceptionif the checksome passed here does not match the checksum calculated remotely.
HPCloud::Exceptionwhen an unexpected (usually network-related) error condition arises.

Definition at line 486 of file Container.php.

References $file, ObjectStorage\$token, ObjectStorage\$url, Object\additionalHeaders(), Object\content(), Object\contentLength(), Object\contentType(), Object\disposition(), Object\encoding(), Object\eTag(), Object\isChunked(), Object\metadata(), Container\METADATA_HEADER_PREFIX, Object\name(), ObjectStorage\token(), and ObjectStorage\url().

setMetadata (   $metadata)

Set the tags on the container.

Container metadata (sometimes called "tags") provides a way of storing arbitrary name/value pairs on a container.

Since saving a container is a function of the ObjectStorage itself, if you change the metadta, you will need to call ObjectStorage::updateContainer() to save the new container metadata on the remote object storage.

(Similarly, when it comes to objects, an object's metdata is saved by the container.)

Names can be no longer than 128 characters, and values can be no more than 256. UTF-8 or ASCII characters are allowed, though ASCII seems to be preferred.

Return values
HPCloud::Storage::ObjectStorage::Container
Returns
$this so the method can be used in chaining.

Definition at line 431 of file Container.php.

References Container\$metadata, and Container\metadata().

Referenced by Container\loadExtraData().

updateMetadata ( Object  $obj)

Update an object's metadata.

This updates the metadata on an object without modifying anything else. This is a convenient way to set additional metadata without having to re-upload a potentially large object.

Swift's behavior during this operation is sometimes unpredictable, particularly in cases where custom headers have been set. Use with caution.

Parameters
object$objHPCloud::Storage::ObjectStorage::Object The object to update.
Return values
boolean
Returns
boolean TRUE if the metadata was updated.
Exceptions
HPCloud::Transport::FileNotFoundExceptionif the object does not already exist on the object storage.

Definition at line 599 of file Container.php.

References ObjectStorage\$token, ObjectStorage\$url, Object\content(), Object\contentType(), Object\metadata(), Container\METADATA_HEADER_PREFIX, Object\name(), and ObjectStorage\url().

url ( )

Get the URL to this container.

Any container that has been created will have a valid URL. If the Container was set to be public (See ObjectStorage::createContainer()) will be accessible by this URL.

Return values
string
Returns
string The URL.

Definition at line 980 of file Container.php.

References ObjectStorage\$url.

useCDN (   $url,
  $sslUrl 
)

Set the URL of the CDN to use.

If this is set, the Container will attempt to fetch objects from the CDN instead of the Swift storage whenever possible.

If ObjectStorage::useCDN() is already called, this is not necessary.

Setting this to NULL will have the effect of turning off CDN for this container.

Parameters
string$urlThe URL to the CDN for this container.
string$sslUrlThe SSL URL to the CDN for this container.

Definition at line 350 of file Container.php.

References ObjectStorage\$url, and ObjectStorage\cdnUrl().

Member Data Documentation

$acl
protected

Definition at line 93 of file Container.php.

$baseUrl
protected

Definition at line 92 of file Container.php.

$bytes = NULL
protected

Definition at line 88 of file Container.php.

$cdnSslUrl
protected

Definition at line 98 of file Container.php.

$cdnUrl
protected

Definition at line 97 of file Container.php.

$count = NULL
protected

Definition at line 87 of file Container.php.

$metadata
protected

Definition at line 94 of file Container.php.

Referenced by Container\newFromResponse(), and Container\setMetadata().

$name = NULL
protected

Definition at line 83 of file Container.php.

$token
protected

Definition at line 90 of file Container.php.

$url
protected

Definition at line 91 of file Container.php.

const CONTAINER_METADATA_HEADER_PREFIX = 'X-Container-Meta-'
const METADATA_HEADER_PREFIX = 'X-Object-Meta-'

The prefix for any piece of metadata passed in HTTP headers.

Definition at line 78 of file Container.php.

Referenced by Container\extractHeaderAttributes(), Container\generateMetadataHeaders(), Container\save(), RemoteObject\setHeaders(), and Container\updateMetadata().


The documentation for this class was generated from the following file: