Creating a product catalog with djondb, PHP Restler and Backbone JS Part III – Services layer


In our previous post, we installed djondb database and used the console to add and retrieve products. In this post, we’ll create the services layer of our application using PHP Restler.

Installing PHP Driver for djondb

Download the djondb PHP driver from djondb downloads page: In this example we will use the OSX version of djondb’s PHP 5.4 driver. Just open the OSX zip file to extract its content (no matter where).

We’ll see the djonwrapper.php file and the modules folder with the file as shown in the following image:

Copy the file that is in the modules folder to this folder: /usr/lib/php/extensions/no-debug-non-zts-20100525/ (the folder may change based on your installation) as shown in the image below. if you are not sure where the folder is, you can execute the command php-config –extension-dir and it will show you the folder configured for extensions.

Once you copy the library file you need to register the module so it can be detected by PHP, to do so you will need to create an ini file, depending on your PHP installation this could change, but the easy way to do this is to use the command php –ini to check where the ini files should be located:

   > php --ini
Configuration File (php.ini) Path: /etc
Loaded Configuration File:         (none)
Scan for additional .ini files in: /Library/Server/Web/Config/php
Additional .ini files parsed:      (none)

So now that we know our folder we can create the djondb.ini file in the folder: /Library/Server/Web/Config/php/djondb.ini (beware that you may need to create this folder if you never installed a PHP extension before). The content of the ini file is as follows:

Finally we have to copy djonwrapper.php to our application rest folder as shown in the following image:

Let’s do a quick test to see if everything is installed and configured properly. First let’s start djondb server (if the server is already running skip this step). Open a terminal window and type:

> djondbd -n
INFO:7fff7b008310: djondbd version 3.5.60107 is starting up.
INFO:7fff7b008310: DBController initializing. Data dir: /var/djondb/
INFO:1042f0000: djondb server ready. Port: 1243
INFO:104373000: web interface ready. Port: 8090. Web Folder: /var/webconsole

We have a test.php file that does the same that the console sample we did in previous post but in PHP. It adds a new product to products namespace and then it retrieves the added product. This is the content of test.php:


$c = DjondbConnectionManager::getConnection("localhost");
$guid = uniqid();
$json = "{ _id: '$guid', name: 'NoSQL Distilled', author: 'Martin Fowler'}";

$c->dropNamespace('demodb', 'products');
$c->insert('demodb', 'products', $json);
echo '<p>Inserted</p>';

echo '<p>Finding</p>';
$res = $c->find('demodb', 'products', '$"name" == "NoSQL Distilled"');

echo $res->toChar();


Open another terminal window and type:

php test.php

<p>Inserted</p><p>Finding</p>{ "_id" : "509fd87630364", "_revision" : "9D96270F-AEB6-4D57-B5D7-FCF797DE6416", "_status" : 1, "author" : "Martin Fowler", "name" : "NoSQL Distilled"}

If you see the above everything is working fine, if not, please check your configuration or check with the forum here:!forum/djondb-support.

Enable PHP on your local Apache

First please verify if you current installation has the PHP module enabled, if not you will need to enable this opening the file: /etc/apache2/httpd.conf and uncommenting the line “LoadModule php5_module..” otherwise your apache installation won’t recognise PHP.

Installing PHP Restler

We’ll use PHP Restler to do the REST magic. Download PHP Restler library from and extract the contents of the file and just copy the restler folder to our application folder as shown in the image below.

Finally we need to configure apache’s URL Rewrite module to support REST URLs. First, open the user’s apache configuration file:

sudo nano /etc/apache2/users/lacho.conf

Modify the file content as shown in the following code:

<Directory "/Users/lacho/Sites/">
Options Indexes MultiViews FollowSymlinks
AllowOverride All
Order allow,deny
Allow from all

And second, create the .htaccess file in the rest folder of the application:

sudo nano .htaccess

And add the following lines to the file:

RewriteBase "/~<user_name>/djonzon/rest"

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteRule ^$ index.php [QSA,L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php [QSA,L]

Replace <user_name> by your user name. Save and close the file, restart the apache server:

sudo apachectl restart

Now everything we need is installed and configured so let’s create the application services layer.

Creating REST Services

As we mentioned in the first post of this series, we want to provide the following functionality to the user:

  1. Browse available products
  2. See product details
  3. Add a new product to the catalog

For testing purposes we have created a file that contains 10 sample products to fill the database. It is a JSON file called products-data.json. To load the products in the database, open a terminal window and type:

djon-shell importProducts.js
Connected to localhost
ns dropped: productsDB ready

Browse available products

First, let’s create a djondb.php file with a Products class inside the rest folder:

class Products {

Now let’s add the get function for retrieving all the products:

function get() {
  $c = ConnectionManager::getConnection("localhost");

  $result = "";
  $res = $c->find('demodb', 'products', '');

  return json_decode($result);

What did we do in the code above?

  • Connect to localhost database server and open the connection
  • Find all the entries in products namespace
  • Concatenate results in a string
  • Return the string in a JSON format

See product details

For simplicity, we’ll use the same get function for getting a specific product. We add an id parameter with a null default value. If id parameter is not null we call findByKey function to get only data of the product with that id.

function get($id=NULL) {
  $c = ConnectionManager::getConnection("localhost");

  $result = "";

  if (is_null($id)) {
    $res = $c->find('demodb', 'products', '');

  } else {
    $res = $c->findByKey('demodb', 'products', $id);
    $result = $res->toChar();

  return json_decode($result);

Add a new product to the catalog

To create a new product we’ll create a POST function that perform an insert to the products namespace with the data sent in the post as JSON. Let’s see the code below:

function post($request_data=NULL) {
  $c = ConnectionManager::getConnection("localhost");

  if (is_null($request_data["_id"])) {
    $request_data["_id"] = uniqid();

  $c->insert('demodb', 'products', json_encode($request_data));

Pretty simple, isn’t it? Now let’s do a quick test of our REST services.

Let’s create an index.php file that references Restler library, djonwrapper library and our business logic code as shown in the code below:

require_once 'restler/restler.php';
require_once 'djonwrapper.php';
require_once 'djondb.php';

$r = new Restler();

Now we open the following URL in the browser and see the loaded products:


We can also test getting a specific product to see if everything is ok: http://localhost/~<user_name>/djonzon/rest/products/50a11ebd3ef70

Ok, we are done with our services layer for the moment. In the next part of this series we’ll create the UI that will consume these REST services, see you then.

Posted in djondb application, NoSQL Samples and tagged .
Loading Facebook Comments ...

Leave a Reply

Your email address will not be published. Required fields are marked *