Considering using MongoDB instead of a SQL DB in your next CodeIgniter project? Well, we were and decided to take a stab at it, and fairly soon discovered that it is pretty straightforward. Even more so, if you don’t try to use CI Active Record, but use native PHP Mongo interface to store and query your data. That suits our case, as we are planning to access the data mostly from Javascript UI over Ajax — in which case it is quite simple to just get the document from Mongo as an array and then serialize it to the UI using PHP JSON functions. Initially I was looking for a way to return JSON objects directly from Mongo (like over the built-in REST interface) to gain some speed, but probably it is not worth the hassle. It is so much easier to take care of authentication, access control, session management and such on the PHP side, because they have to be built into the application anyway; conversion from BSON to PHP array to JSON is not that heavy that it would affect performance too much.

However, even if I can live without the CodeIgniter Active Record, I didn’t want to give up the good stuff in the CI_Session class and do session management using native PHP sessions. I took a look at CI Session.php and found a way to extend it so that the existing code can be (mostly) reused. The implementation would be nicer if the CI_Session class was actually designed for extension with DB functions extracted so that they could be easily overridden to use a different kind of storage. My approach relies on the internal implementation of the session manipulation functions and can easily break when CI version changes. The implementation is based on 1.7.2 and tested only on that; if you want to use it on a different CI version, be prepared to read the Session.php of that version and tweak the Mongo session implementation accordingly.

You can download my implementation here; the package contains a README for installation instructions. The sessions will be persisted to MongoDB instead of SQL — otherwise they behave exactly as before.

About these ads