Over a million developers have joined DZone.

Playing with PHP, CouchDB and ORM

· Web Dev Zone

Start coding today to experience the powerful engine that drives data application’s development, brought to you in partnership with Qlik.

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.

Create data driven applications in Qlik’s free and easy to use coding environment, brought to you in partnership with Qlik.


Published at DZone with permission of Gonzalo Ayuso, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

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

{{ parent.tldr }}

{{ parent.urlSource.name }}