Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDB and CodeIgniter [closed]

Can anyone assist in pointing me to a tutorial, library, etc. that will allow me to work with MongoDB from CodeIgniter?

like image 551
IEnumerator Avatar asked Feb 12 '10 00:02

IEnumerator


1 Answers

I'm not sure if its the "CodeIgniter way" but I created a CodeIgniter library that extends the Mongo class with an extra property to store the current database connection.

Here are the relevant code files from my project.

config/mongo.php

$config['mongo_server'] = null; $config['mongo_dbname'] = 'mydb'; 

libraries/Mongo.php

class CI_Mongo extends Mongo {     var $db;      function CI_Mongo()     {            // 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');         $dbname = $ci->config->item('mongo_dbname');          // Initialise Mongo         if ($server)         {             parent::__construct($server);         }         else         {             parent::__construct();         }         $this->db = $this->$dbname;     } } 

And a sample controller

controllers/posts.php

class Posts extends Controller {     function Posts()     {         parent::Controller();     }      function index()     {         $posts = $this->mongo->db->posts->find();          foreach ($posts as $id => $post)         {             var_dump($id);             var_dump($post);         }     }      function create()     {         $post = array('title' => 'Test post');         $this->mongo->db->posts->insert($post);         var_dump($post);     } } 
like image 118
Stephen Curran Avatar answered Sep 26 '22 05:09

Stephen Curran