Saturday, January 08, 2011

Using Redbean with Code Igniter 1.7.3

I started playing around with codeigniter for a quick project, and wanted a simple ORM for manipulating databases quickly. After looking briefly at RedbeanPHP, I decided to give it a spin. Boris Strahija had actually shown how to do it last year in the forums, but I just wanted to post my files for reference. This assumes the database.php file in your config dir is already pointing to a valid database. I was using mysql.

  1. Download RedbeanPHP and drop the two files (._rb.php and rb.php) in system/application/libraries
  2. Create a library class called Redbean.php with the contents shown below, and drop it in the same directory
  3. Use it in your controller

Redbean.php
ci =& get_instance();

// Include database configuration
include(APPPATH.'/config/database.php');

// Include required files
include(APPPATH.'/libraries/rb.php');

// Database data
$hostname     = $db[$active_group]['hostname'];
$username     = $db[$active_group]['username'];
$password     = $db[$active_group]['password'];
$database     = $db[$active_group]['database'];

// Create RedBean instance
$toolbox = RedBean_Setup::kickstartDev('mysql:host='.$hostname.';dbname='.$database, $username, $password);
$this->ci->rb = $toolbox->getRedBean(); 
    }
}

Using it somewhere in your controller
// example code of creating a 'post' table
$post = $this->rb->dispense("post");
$post->title = 'My first post from CodeIgniter';
$post->body ='Lorem ipsum dolor sit amet, consectetur adipisicing elit....';
$post->created = time();
$id = $this->rb->store($post); 

After running this controller, you should see a 'post' table created. Done!

What you should see in phpMyAdmin