I like the Stephen Curran example because it is simple and allows the Mongo interface, not too much functionality written in Php, I tend to find huge abstractions several times for what I will be doing.
I expanded my example to include database authentication. Go here: http://www.mongodb.org/display/DOCS/Security+and+Authentication to read about mongo authentication, remember to enable authentication for the Mongo Server you are connecting to.
I also changed the old-style constructor function as __construct and handle Mongo Connection Exceptions, as they can show 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';
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')); } } }
Luke Tarplin Nov 18 '11 at 17:33 2011-11-18 17:33
source share