I like Stephen Curran's example as it is simple and allows an interface to Mongo without too much functionality written within Php, I tend to find huge abstraction clases a bit much at times for what I am after.
I have extended his example to include database authentication. Go here: http://www.mongodb.org/display/DOCS/Security+and+Authentication to read about mongo authentication, don't forget to enable authentication for the Mongo Server you are connecting to.
I have also changed the old style constructor function to be __construct and am handling Mongo Connection Exceptions as they can reveal your username and password.
config/mongo.php
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
$config['mongo_server'] = 'localhost';
$config['mongo_dbname'] = 'my_mongo_db';
$config['mongo_username'] = 'mongo_user';
$config['mongo_password'] = 'password1234';
/* End of file mongo.php */
libraries/Mongo.php
<?php
class CI_Mongo extends Mongo{
protected $db;
function __construct()
{
// Fetch CodeIgniter instance
$ci = get_instance();
// Load Mongo configuration file
$ci->load->config('mongo');
// Fetch Mongo server and database configuration
$server = $ci->config->item('mongo_server');
$username = $ci->config->item('mongo_username');
$password = $ci->config->item('mongo_password');
$dbname = $ci->config->item('mongo_dbname');
// Initialise Mongo - Authentication required
try{
parent::__construct("mongodb://$username:$password@$server/$dbname");
$this->db = $this->$dbname;
}catch(MongoConnectionException $e){
//Don't show Mongo Exceptions as they can contain authentication info
$_error =& load_class('Exceptions', 'core');
exit($_error->show_error('MongoDB Connection Error', 'A MongoDB error occured while trying to connect to the database!', 'error_db'));
}catch(Exception $e){
$_error =& load_class('Exceptions', 'core');
exit($_error->show_error('MongoDB Error',$e->getMessage(), 'error_db'));
}
}
}