Hello, this is Jan Lehnardt and you're visiting my blog. Thanks for stopping by.
plok — It reads like a blog, but it sounds harder!
↑ Archives
Update: 19.11.2006
This Tutorial is outdated, see the CouchDb PHP Hello World Tutorial at the CouchDb Wiki.
This HowTo explains how to write PHP applications that use CouchDb as there data storage. It assumes you are familiar with PHP’s syntax and at best you already wrote some code for a project. It’s also good to know about databases and how and why to use them in PHP applications. If you never heard about classes and objects, you might be able to follow the examples anyway, so don’t worry about that.
The HowTo also assumes you’ve installed CouchDb according to the installation instructions. Then Download the CouchDb PHP Library and unpack into your project’s directory.
CouchDb offers a REST API to all it’s functionality. Using it is pretty straightforward: Issue a specially crafted HTTP request to the CouchDb daemon and wait for a response. To create a database, for example, you create a PUT request and send it to http://couchdb/articles. CouchDb answers with a 200 HTTP status telling you everything went well.
In the course of developing an application for CouchDb, you’ll quickly notice that it is a good idea to put all that talking to CouchDb into separate functions, just as it made sense, to put away all the MySQL interaction code into it’s own package on your last project.
Luckily, CouchDb comes with a PHP class that takes care of all the nasty details. Go CouchDb! This HowTo explains how to use this class. We start with an example:
<?php
// include the library file
include 'Library/CouchDb/Couch.php';
// we run CouchDb locally and
// we run it on its standard port
$server = 'localhost';
$port = 8888;
$database = 'messages';
// create a new Couch object
$couch = new Couch($server, $port, $database);
// create our database
$couch->create();
// create document...
$document['Subject'] = 'Hello Ma';
$document['Message'] = 'I hope you enjoy your
vacation! Best, Sonny';
// ...and save it
$couch->save_document($document);
echo "Successfully saved your document
under the id :{$couch->lastDocId}";
?>
That is just a couple of lines of code and you already created you first document in CouchDb! But let’s go through the examples step by step.
At first, you have to include the Couch.php file. If you adjusted the installation procedure to your needs, you may have to change a few things, here. But that should be an easy task.
The example then creates a new Couch object using the previously defined values. A Couch object represents the connection to a single database in a CouchDb daemon. The server runs on ‘localhost’ on port 8888 and your database will be named ‘messages’.
To store documents into CouchDb we first have to create a database to put it into. CouchDb can handle several databases at once, but for this HowTo we need only one.
Then we set up an associative array. It’s keys hold the names of the fields our document will have. The array is then handed to the $couch->save_document($document);
method which, duh, saves our document.
This is not very impressive yet, since there is not much to see. But we can verify that something actually happened.
Point your web browser to http://localhost:8888/$utils/peek.html (again, assuming, your instance of CouchDb is running there). You’ll see peek, CouchDb’s built in administration tool. As the time of writing this HowTo (CouchDb version 0.5.0), peek can’t do a lot, but it can tell you that the example works. In the left column, you should see your database and when you click on it on the right the contents of the database are shown. Have look at the Peek Example View.
You can see a 32 Bit long document id on the right side. This is the identifier you document is uniquely associated with. No other Document in the database can have this id.
To get back this document, simply do
$document = $couch->get_document($docId);
Now saving and retrieving a single document is not most thrilling thing to do. Assuming you’ve been inserting a couple of documents, you surely want to retrieve them in groups. To do this you need Computed Tables.
A Computed tables defines a specialized view on your documents. You can define them to show all your documents, or just a subset and you can let CouchDb sort the documents for you.
The definitions for Computed Tables are expressed in the Fabric Formula language. You specify a criterion that matches your documents and the fields you want to retrieve.
SELECT *
COLUMN CreationDate
COLUMN Subject
COLUMN Message
This table matches all your documents (SELECT *
) and retrieves the three fields CreationDate
, Subject
and Message
.
A Computed Table belongs to a database and a database can have as many tables as you wish. To tell our database to create the table above we do
$table = 'SELECT *
COLUMN CreationDate
COLUMN Subject
COLUMN Message';
$couch->add_table($name = 'all', $tables);
The $couch->add_table();
method takes two arguments; the first is the name of the table and the second is a string containing the Fabric definition. To add multiple tables with a single command you can create an associative array with the names of the tables as keys and their definitions as values and send it with the $cuoch->add_tables($tables);
method.
$tables['all'] = 'SELECT *
COLUMN CreationDate
COLUMN Subject
COLUMN Message';
$tables['short'] = 'SELECT length(Message) < 100
COLUMN CreationDate
COLUMN Subject
COLUMN Message';
$couch->add_tables($tables);
Once the Computed tables are in place you can start querying them. A query to a table is as straightforward as asking it to return all documents that match the SELECT
line for this table.
$shortMessages = $couch->get_documents('short');
foreach($shortMessages AS $id => $message) {
?><p><?php
echo $message['Subject'];
echo $message['Message'];
?></p><?php
}
The documents returned are sorted by the first COLUMN
defined for the table. Along with reversing the order, there are several options you can give $couch->get_documents();
to influence the result.
$shortMessages = $couch->get_documents('short',
$options = array('reverse' => 'true',
'count' => 10));
foreach($shortMessages AS $id => $message) {
?><p><?php
echo $message['Subject'];
echo $message['Message'];
?></p><?php
}
Prints the same as the last example, only in reverse order and only 10 documents.
That concludes this little tutorial. I hope to get you hooked on CouchDb. If you have any questions or additions feel free to change this document or drop me a line at jan at php dot net. For a more recent version, you can always look at the CouchDb Wiki