Web Programming TutorialsLearn How To Create Your CouchDB Document With PHP

Learn How To Create Your CouchDB Document With PHP

When it comes to PHP development, the most used database that comes to everyone’s mind is MySql. MySql is the well supported database and almost 90% of the websites that are built using PHP uses MySql at the backend. Having said that, MySql is not the only database that doesn’t fits in everything . For example, MySql is not built to handle schema-less data.

There are hacks that MySql users usually come up with but such problems that does not solve the real purpose and are often complicated to use. The programming community has been introduced to the NoSql databases which are quite efficient to handle schema-less data. In this article, we will walk you through the general usage of a NoSql database i.e. Apache CouchDB with PHP.

General Usage

Apache CouchDB consists of databases and documents. Databases are a set of documents. The documents are actually JSON documents which are capable of storing data such as arrays, strings, numbers and even binary data in the form of attachments. So basically, CouchDB assigns a unique ID to every document that is stored in the database unless you supply a preferred ID while storing the document. CouchDB exposes its functionality via an HTTP REST protocol. You can even use plain cURL commands to use CouchDB. You can also use plain Javascript from your browser to access CouchDB without the need of any server side implementation.

In PHP, you can either use the php cURL functions to directly access CouchDB REST API or you can use a wrapper library which is built on top of the REST API itself. Many such libraries have been built on top of the CouchDB API. For this article we will be using PHP-on-Couch to access our CouchDB database. Without further ado, let’s start coding.

Setting up and Installing the library

You can directly download this library from its Github page or you can install the library using Composer. You can use the following command to install this library using Composer:

$ composer require php-on-couch/php-on-couch

Make sure to include the vendor autoload file into your php file after executing the above command as follows:

<?php
# initializing composer
require __DIR__ . '/vendor/autoload.php';
?>

For this article, I assume that you have already installed PHP and CouchDB on your local machine, and created a database named superheroes in which we will be keeping all of our documents. You can easily create this database using cURL with the following command:

$ curl -X PUT

We are actually making an HTTP PUT request to the CouchDB endpoint with our database name i.e. superheroes. You are only required to run this command once, running it more than once will return an obvious error stating that the database already exists.

Making a database connection

The PHP-on-couch library comes with a couchClient class, whose instance we need to create in order to access our database. You can create multiple instances at once to different CouchDB servers as well. Following is how we create our CouchDB instance:

<?php
# initializing composer
require __DIR__ . '/vendor/autoload.php';

# the CouchDB client object
use  PHPOnCouch\CouchClient;

# making a db connection
$client = new couchClient(
	"http://localhost:5984/", # host / DSN
	"superheroes" # database # this database must exist
);

We are storing our database connection resource in the variable named $client. We will further use this variable for all our transactions with the CouchDB server.

Getting database information

The following command returns general information about our database to which we are connected. In our case, all data related to the supereroes database will be returned.

$dbs_info = $client->getDatabaseInfos();
print_r($dbs_info);

The above script will output an object with the information in the following format:

stdClass Object
(
	[db_name] => superheroes
	[doc_count] => 2
	[doc_del_count] => 4
	[update_seq] => 18
	[purge_seq] => 0
	[compact_running] =>
	[disk_size] => 73832
	[data_size] => 1613
	[instance_start_time] => 1516115579615774
	[disk_format_version] => 6
	[committed_update_seq] => 18
)

Printing all available databases

Just in case you wish to see all available CouchDB databases on your server, you can use the following php function:

$databases = $client->listDatabases();
print_r($databases);

The above code will output an array consisting of the names of all the available database on the server.

Array
(
	[0] => _replicator
	[1] => _users
	[2] => superheroes
)

_replicator and _users databases are for CouchDB’s internal use. The superheroes database is where we will be storing all our data.

Creating our first CouchDB document

In our superheroes database, we will now create our first document, which would be the profile of Ironman. Though, you can assign your own ID to this document, for the examples in this article, we let CouchDB to itself choose IDs for our documents. The code to create our very first record is as follows:

$ironman = new stdClass();
$ironman->real_name = "Anthony Stark";
$ironman->alias = "Tony";
$ironman->superhero_specifics = [
	'weapons' => [
    	'Repulsors',
    	'Missiles',
    	'Unibeam',
    	'Lasers',
    	'Shoulder mounted Guns',
    	'Flares'
	],
	'abilities' => [
    	'Nuclear Powered Energy Core, known as "Arc Reactor"',
    	'AI Armored Suit',
    	'Super Strength',
    	'Flight',
    	'Diving',
    	'Space Travel'
	]
];
$ironman->love_interest = 'Virginia "Pepper" Potts';
$response = $client->storeDoc($ironman);

So, basically we first create an empty object and then add object properties to it. You can store simple strings, numbers or arrays to your documents. Once done, a function named storeDoc() is finally called to store our document in the database. This document is stored in our database with a unique ID.

On successful creation, an array is returned as follows:

(
	[ok] => 1
	[id] => 8ed2a4b132a76ca18b68e4871d000859
	[rev] => 1-aaddd73c6e6c9c767a422b81b64e798c
)

Fetching all available documents and print their data

In order to fetch contents if all the documents saved in your CouchDB database, you can run the following command:

$all_heroes = $client->getAllDocs();
foreach($all_heroes->rows AS $the_key => $the_hero){
	print_r($client->getDoc($the_hero->id));
}

As you have just one record in your database, you will see all the data stored for that particular record. All records are returned as PHP objects consisting of all the document data that we set above. You will notice two extra fields named _id and _rev as well. These are auto assigned with very document. _id is the document id and _rev is the revision number. Revision number is auto assigned at the time of document creation and it keeps on updating itself with every document updation request. Infact, we need to specify the revision number when updating our documents. This functionality will be covered later in this article. The revision number can be thought of similar functionality as in version control softwares.

Creating our second document

We now proceed with creating our second document as follows:

$captain = new stdClass();
$captain->real_name = "Steve Rogers";
$captain->alias = "Cap";
$captain->superhero_specifics = [
	'weapons' => [
    	'Vibranium Steel Alloy Shield',
    	'M1911A1 Handgun'
	],
	'abilities' => [
    	'Super Human Strength',
    	'Super Human Agility',
    	'Super Human Speed',
    	'Super Human Endurance',
    	'Super Human Reaction',
    	'Bodily Functions to the peak of Human Efficiency'
	]
];
$captain->love_interest = 'Peggy Carter';
$response = $client->storeDoc($captain);

The above document will be auto assigned a new ID and a revision number apart from the data we are storing in this document.

Updating the first document

Now we have two documents stored in our database. Lets update our first document by adding an ability record to the Ironman document. You should know the ID of the document for updating it . You also need the revision number, but if you know the ID, we can easily fetch the revision number of the document before updating it. You probably need to save these IDs in a separate table altogether. The methodology of updatng the CouchDB document is simple and straight forward. Firstly, you fetch the complete document and store it in a variable, then make changes in it. Lastly you save this document using the document ID and the latest Revision Number. This means, you can completely wipe out all of the document data and insert all new data with different keys to the same document, you are not bound to any schema when working with CocuhDB. I the following example, we make just a slight change and add an ability to our Ironman document:

$iron_man_doc_id = '8ed2a4b132a76ca18b68e4871d002c2b'; # you already need to know this
$ironman_record = $client->getDoc($iron_man_doc_id);
$iron_man_doc_rev = $ironman_record->_rev;
$updated_ironman_record = $ironman_record;
$updated_ironman_record->superhero_specifics->abilities[] = 'Money';
$response = $client->storeDoc($updated_ironman_record);
print_r($updated_ironman_record);

In the above code, we already know the document id, using which we fetch our document data. We store the current revision number in a variable. We assign the returned object to a new variable and make changes to the contained data. Lastly, we save this updated data using the document id and revision number. The revision number should always be the latest one when updating the documents.

Deleting the document

Deleting the CouchDB document is almost similar to updating a document. We need to fetch the document using the Unique ID, and then call the deleteDoc function with the fetched document being supplied as the parameter to this function. Following is how we do it:

# deleting documents
$hero_record_to_delete = new stdClass();
$iron_man_doc_id = '8ed2a4b132a76ca18b68e4871d0021b1'; # you must already know this
$ironman_record = $client->getDoc($iron_man_doc_id);
$result = $client->deleteDoc($ironman_record);
print_r($result);

The above code completely removes our document.

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Exclusive content

- Advertisement -

Latest article

21,501FansLike
4,106FollowersFollow
106,000SubscribersSubscribe

More article

- Advertisement -