Database Reference
In-Depth Information
GridFS and the PHP Driver
The previous chapter elaborated on GridFS and its benefits. For example, it explained how to use this technology to
store and retrieve data, in addition to other GridFS-related techniques. In this section, you'll learn how to use the PHP
driver to store and retrieve files using GridFS.
The PHP driver contains its own classes for dealing with GridFS; here are three of its most important classes and
what they do:
MongoGridFS : Stores and retrieves files from the database. This class contains several methods,
including delete() , find() , storeUpload() , and about a half dozen others.
MongoGridFSFile : Works on a specific file in the database. It includes functions such as
__construct() , getFilename() , getSize() , and write() .
MongoGridFSCursor : Works on the cursor. It contains a handful of functions, such
as __construct() , current() , getNext() , and key() .
Let's have a look at how we can use PHP to upload files into the database.
the code in the following example will not work without an htML form that uploads data. Such code is beyond
the scope of this chapter, however, so it is not shown here.
Note
Storing Files
You use the storeUpload() function to store files into your database with GridFS. This function takes two parameters:
one indicates the fieldname of the file to be uploaded, and the other can optionally be used to specify the file's
metadata. Once used, the function reports back the _id of the file stored.
The following simple code example shows how to use the storeUpload() function:
// Connect to the database
$c = new MongoClient();
// Select the name of the database
$db = $c->contacts;
// Define the GridFS class to ensure we can handle the files
$gridFS = $db->getGridFS();
// Specify the HTML field's name attribute
$file = 'fileField';
// Specify the file's metadata (optional)
$metadata = array('uploadDate' => date());
// Upload the file into the database
$id = $gridFS->storeUpload($file,$metadata);
And that's all there is to it. As you can see, $id is used as a parameter to store the file in the database. You might
also use this parameter to reference the data with DBRef.
 
 
Search WWH ::




Custom Search