Skip to content

examples

Lorna Jane Mitchell edited this page Feb 25, 2018 · 7 revisions

This is the place to come for more-than-API-docs. Check out the various sections to help with common tasks - and open an issue to share or request an example that isn't listed.

Fetch and display a list of documents

We can get all the documents from the database. Each one arrives as a \PHPCouchDB\Document object with top-level properties that represent the values. If I try it on my shopping list app where every document has an "item" property, then the code looks like this:

<?php

require "vendor/autoload.php";

$server = new \PHPCouchDB\Server(["url" => "http://localhost:5984"]);
$my_db = $server->useDb(["name" => "shopping"]);

$docs = $my_db->getAllDocs();
foreach($docs as $doc) {
    echo "I am a doc, with item value: " . $doc->item . "\n";
}

I get output like this:

I am a doc, with item value: milk
I am a doc, with item value: bread
I am a doc, with item value: eggs

Identify an update conflict

CouchDB has databases that contains documents; each document has both an id and a revision. By knowing which revision, or version, of a document we're working on at any one time, we can avoid accidentally overwriting data or deleting records that have changed. When you fetch a document from CouchDB, the PHPCouchDB library also fetches its revision. When you update it, a whole new PHPCouchDB\Document object is returned, to reflect the new revision that was created. However if an update is attempted on an old revision, this will fail.

Here's the code showing two document updates - the second one will fail because the first update creates a newer revision of the document.

<?php

require "vendor/autoload.php";

$server = new \PHPCouchDB\Server(["url" => "http://localhost:5984"]);
$database = $server->useDb(["name" => "phplib"]);

$doc = $database->create(["name" => "Tinker Bell"]);

try {
    $doc->colour = "green";
    $newdoc = $doc->update();
    echo "Doc updated once\n";
    // calling update on an old object causes a conflict
    $newdoc2 = $doc->update();
    echo "Doc updated twice\n";
} catch (\PHPCouchDB\Exception\DocumentConflictException $e) {
    // we are updating an old version of the record, take evasive action!
    echo "Oops, let's get the current version and try again.\n";
}

By catching the \PHPCouchDB\Exception\DocumentConflictException case speciifically, we can handle the situation where the document changed since we last fetched it. The correct evasive action will depend on the context but in most cases, it is enough to fetch, alter and update the document again. If you're seeing this error often, check that you're assigning the return value of the update() method - the old object can't be used again once we've created a new revision.

Get data from a view

In the simplest case, you can just call Database::getView and supply an array including the Design Document ddoc and View view:

<?php

require "vendor/autoload.php";

$server = new \PHPCouchDB\Server(["url" => "http://localhost:5984"]);
$database = $server->useDb(["name" => "phplib"]);

$view = $database->getView(["ddoc" => "mydesigndoc", "view" => "myview"]);

This returns an array of arrays, a pretty unchanged reflection of what CouchDB itself returns - the exception is if you are including the documents themselves, an example on that in a moment....

CouchDB isn't terribly helpful with view by default - usually you want to include either group = true or group_level = 1 (or 2 or whatever makes sense for the grouping you'll be using.

<?php

require "vendor/autoload.php";

$server = new \PHPCouchDB\Server(["url" => "http://localhost:5984"]);
$database = $server->useDb(["name" => "phplib"]);

$view = $database->getView(["ddoc" => "mydesigndoc", "view" => "myview", "group_level" => 2]);

If you're not reducing the view, but just using it for filtering and want to return the documents as well then include both reduce=false and include_docs=true. When the docs are present in the response, CouchDB will turn them into \PHPCouchdb\Document objects as it does when fetching with getAllDocs().

You can pass any other parameters to getView that should be supplied to the HTTP request as query parameters, e.g. key or limit. If you see anything strange then please open an issue, there are probably combinations that we don't have tests for yet.

Additional Connection Requirements

If you need any additional configuration of the HTTP connection, then you can supply a "client" element to the constructor's array argument, and pass any \GuzzleHttp\ClientInterface object to that. Check the documentation of Guzzle Request Options as all of these can also be passed in the constructor of the \GuzzleHttp\Client.

<?php

require "vendor/autoload.php";

$client = new \GuzzleHttp\Client([
    "base_uri" => "http://localhost:5984"
    // set any other options here
]);

$server = new \PHPCouchDB\Server(["client" => $client]);
echo $server->getVersion();

Need Functionality That Isn't Supported

First of all: open an issue so we know what you looked for and missed.

Then, use \PHPCouchDB\Server::getClient to get the \GuzzleHTTP\Client. Since CouchDB is a pure HTTP interface, you can use the client and the excellent Guzzle documentation to do whatever it is you need.