Over a million developers have joined DZone.

Playing with PHP, CouchDB and ORM

DZone's Guide to

Playing with PHP, CouchDB and ORM

· Web Dev Zone ·
Free Resource

Read this guide to learn everything you need to know about RPA, and how it can help you manage and automate your processes.

I’m playing with PHP and CouchDB. After writing a class to connect PHP and CouchDB I’ve done a variation of the interface to use CouchDB with PHP in a similar way to ORM. Yes. I know ORM means Object Relational Mapping and CouchDB isn’t a Relational Database but have a look to the following interface:

Imagine you have a CouchDb at localhost:5987 and you have a database called users.

Now let’s build a class called CDB_Users.

class CDB_Users extends Nov_CouchDb_Orm {
    static $_db = 'users';

It’s easy to automate the creation of CDB_Users with a script

CDB_Users extends Nov_CouchDb_Orm

class Nov_CouchDb_Orm
    static protected $_db;

     * @param string $key
     * @return Nov_CouchDb
    static public function connect($key)
        $class = get_called_class();

        $couchDb = new Nov_CouchDb($host, $port, $protocol, $user, $password);
        return $couchDb->db($class::$_db);

A configuration class:

class Nov_CouchDb_Conf
    const CDB1 = 'CDB1';

    private static $_conf = array(
        self::CDB1 => array(
            'protocol' => 'http',
            'host'     => 'localhost',
            'port'     => 5984,
            'user'     => null,
            'password' => null

    static function get($key)
        return self::$_conf[$key];

Putting all together with the class Nov_CouchDb
we can use:

CDB_Users::connect(Nov_CouchDb_Conf::CDB1)->insert('gonzalo', array('password' => 'g1'));
$data = CDB_Users::connect(Nov_CouchDb_Conf::CDB1)->select('gonzalo')->asArray();

CDB_Users::connect(Nov_CouchDb_Conf::CDB1)->update('gonzalo', array('password' => 'g2'));
$data = CDB_Users::connect(Nov_CouchDb_Conf::CDB1)->select('gonzalo')->asArray();


What do you think? That’s not exactly a ORM. I’m not sure if I will use that interface instead the classic one.

$data = CDB_Users::connect(Nov_CouchDb_Conf::CDB1)->select('gonzalo')->asArray();
// versus
$couchDb = new Nov_CouchDb('localhost', 5984);
$data = $couchDb->db('users')->select('gonzalo')->asArray()

Here is the full source code with the examples.

Get the senior executive’s handbook of important trends, tips, and strategies to compete and win in the digital economy.


Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}