MongoDB Base Model for Zend Framework

I came accross MongoDB a few months ago and it seemed like a perfect fit for many of the projects I am working. Extremely fast inserts, map-reduce for complex queries, and most importantly, scaling is a breeze.

Since I am a Zend Framework guy I created a simple base model class for MongoDB. It is a very simple wrapper, but is effective for what I need. I usually create model classes for each “Collection” just like I would create models for each table in MySQL. Each model class extends from the new MongoDB base class and allows a low level “active directory” type access to MongoDB documents.

Get The Source Code Here

Example: We want to create a new document for every visitor that comes into a website that we are tracking. We store those documents in the “visitor” collection.

The first thing we do is create a model for the visitor collection.

class Model_Visitor extends Mongodb_ModelBase {

    // If you don't specify the collection name explicitly,
    // it will default to the name of the class minus the "Model_" part.
    protected static $_collectionName = "visitor";


Then we can create new documents for that collection

$newVisitor = new Model_Visitor();
$newVisitor->ipAddress = '';

You can also query for visitors using static methods:

$oneVisitor = Model_Visitor::findOne();
$allVisitors = Model_Visitor::find();
$someVisitors = Model_Visitor::find(array('ipAddress'=>''));

Use dot notation for nested values. These two commands do the same thing:

$myVisitor->{'referrer.url'} = '';
$myVisitor->referrer = array('url'=>'');

I thought I would share this with the rest of the world in case someone needed it.

Get The Source Code Here

NOTE: The base class makes use of late static binding, which requires PHP 5.3

More Reading
Older// Contact
comments powered by Disqus