Using ActiveRecord Library Separately from CodeIgniter


CodeIgniters ActiveRecord library is a nice implementation (though modified) of ActiveRecord design pattern. It comes bundled with CodeIgniter. So if you want to use Just this library in your application individually instead of using full CodeIgniter framework, what to do?

Today I’ve spent some time and separate the ActiveRecord library from CodeIgniter. Now you can use it via a class named ActiveRecordFactory. Here’s how to do it (I separate only the MySQL driver) .

I separate the “database” folder under the “system” directory of CodeIgniter. Then I removed all folders in database/drivers except “mysql”. (I need only MySQL, :D )

I modified the class definition at database/drivers/mysql_driver.php
Previously It Was : class CI_DB_mysql_driver extends CI_DB {
Now : class CI_DB_mysql_driver {

I modified the class definition at database/DB_driver.php
Previously It Was : class CI_DB_driver {
Now : class CI_DB_driver extends CI_DB_mysql_driver {

And finally I create a ActiveRecord Factory to instantiate codeigniters Active Record Properly. Here is the code

File: database/ActiveRecordFactory.php


<?
/**
 * This is a Factory to create an instance of Code Igniters Active Record Class
 *
 * @author Hasin [http://hasin.wordpress.com]
 */

define(BASEPATH,"./");
include_once (
"drivers/mysql/mysql_driver.php");
include_once (
"DB_driver.php");
include_once (
"DB_active_rec.php");
include_once (
"DB_result.php");
include_once (
"drivers/mysql/mysql_result.php");

function log_message(){/*just suppress logging*/}

Class ActiveRecordFactory {
    private static 
$dsn;
    private static 
$CIAR;
    public static function 
Factory($dsn=null)
    {
        if (!empty(
$dsn)) self::$dsn $dsn;
        if (empty(
self::$CIAR))
        {
            if (!empty(
self::$dsn))
            
self::$CIAR = new CI_DB_active_record($dsn) ;
            else 
            throw new 
Exception("Please give a DSN in this format 'driver://username:password@hostname/database'");
        }
        return 
self::$CIAR;
    }
}
?>

Now You can test The ActiveRecord library like this

<?
include(“database/ActiveRecordFactory.php”);
$activerecord = ActiveRecordFactory::Factory(“mysql://user:password@localhost/test”);
$activerecord = ActiveRecordFactory::Factory();

$activerecord->select(“name”);
$activerecord->where(“id=”,”10″);
$activerecord->orwhere(“id=”,”19″);
print_r($activerecord->get(“users”)->result_array());

$activerecord->select(“name”);
$activerecord->where(“id=”,”10″);
$activerecord->orwhere(“id=”,”19″);
echo $activerecord->get(“users”)->num_rows();

$activerecord->insert(“users”,array(“name”=>”CodeIgniter”,”pass”=>”CI Rocks”));
?>

You can download the complete example from here http://hasin.javapark.net/ActiveRecord.zip

About these ads

31 thoughts on “Using ActiveRecord Library Separately from CodeIgniter

  1. Pingback: developercast.com » Hasin Hayder’s Blog: Using ActiveRecord Library Separately from CodeIgniter

  2. Looks good,
    you should be able to use

    $activerecord->where(”id”,”10″);
    $activerecord->orwhere(”id”,”19″);

    instead of

    $activerecord->where(”id=”,”10″);
    $activerecord->orwhere(”id=”,”19″);

    No big deal but looks just a bit cleaner.

  3. Pingback: PHPGeek » Standalone ActiveRecord Library from CodeIgniter

  4. You can also check out myActiveRecord, a standalone ActiveRecord class for mysql (as of right now, hopefully more db support soon). I tried to make the syntax as simple as possible to use. Its slightly different from CI, in that it uses camelcase dynamic functions, like: $db->findUsernameWhere(“id=$id”);

    Thanks!
    Wess

  5. thank you very much for this!

    one thing: in DB_driver.php, there is a method display_error that uses a library from CodeIgniter. i think it’s a good idea to change it for printing out the error message and die, instead of using the Exceptions library.

  6. Hi there. This is a great idea. I have followed your instructions but PHP is generating an error at line 18: “private static $dsn;”

    Any ideas why this might be? Also as ibnoe has mentioned, the download URL is broken. Any chance of fixing this up? :)

  7. its me again. i wanted to tell you again that after integrating your ci active_record, my coding live changed completely – and that makes me very happy. my code looks wonderful now, I threw out that adodb – which i really hated from all the beginning.

    1.000.000 thanks for that!

    i hope very much you go on to extract perhaps the complete loader class or maybe more ci classes as the very nice template or validation…

    please do more of that, its fantastic to work with the separated ci classes in existing projects!

  8. Thanks for this. I had just decided that CodeIgniter wasn’t quite right for me. However, I loved ActiveRecord; so, I was going to do the same thing you’ve done.

    Now that I’ve found this, I can just get started instead of having to figure it out myself.

  9. Pingback: Super Scratch Development-1: Ideas from CodeIgniter & Drupal « Everyone should get a 2nd chance

  10. Pingback: Using Validation Library Separately from CodeIgniter « Everyone should get a 2nd chance

  11. Could you post a php4 version? I tried to do it myself thinking you could just switch up a few things. But unfortunatley it didnt work.

  12. With tCI 1.7 this is no longer needed, now there is a function DB() in the which can receive a dsn as parameter. All you need to do is define BASEPATH and EXT, include “database/DB.php” and define function log_message(){}

    Works like a charm! :)

  13. @eljunior: Not if you want to use the active record set parts of the class.

    Theres a whole bunch of methods that need to be over-riden etc.

  14. Pingback: Documentopia » Code CodeIgniter ActiveRecord – Stand Alone Version

  15. Nice.. My variant is

    @define(BASEPATH,’./core/’);//folder, contain database classes
    @define(APPPATH,’./’);
    @define(EXT,’.php’);
    function log_message($text){
    /*echo ‘<div style="color:green"><h3>Log</h3>’.$text.’</div>’;*/
    }
    require_once(‘core/database/DB.php’);
    function instantiate_class($class){
    return $class;
    }
    $DB = DB();
    $query = $DB->get(‘users’);
    foreach ($query->result_array() as $row)
    {
    print_r($row);
    }

    no Changes in Classes
    Can get config like CI from APPPATH/config/database.php

  16. @Michail1982: Excellent tip, thanks !

    If someone doesn’t want to use the config file, they can just call the DB() function with the dsn like this:


    $db = DB("mysql://root:test123@localhost/storyteller");

  17. I am not able to download the zip file.. its looking dead link.

    and if goes according to the step mentioned above.. i m getting the following error.

    Fatal error: Call to a member function num_rows() on a non-object

  18. require_once(‘core/database/DB.php’);
    function instantiate_class($class){
    return $class;
    }

    will this execute if i put it in my code or are those just name spaces . I know core refers to the base path what of instantiate_class ? Also $class should be the DB function right, cause i am looking at it right now and i dont see where that block of code comes in.

    • Dear Sulaemanhow are you?I’m just playing aurond with the balita theme. Now I’m at a critical point. When I open the shop, at the first page are just product pictures. Is it also possible to show categorie pictures instead? That would be pretty cool.Is it possible and how much would it cost to chage it like that? Thank you very much for your help.With best regards,Tobi

  19. Hello there everyone,
    First I’d like to thank You hasin for excellent library separation. Now I don’t know if You’ve heard of Smarty templates engine, but I’m trying to use it with this library, and I’ve faced couple of problems.
    Basically my code should work like this:
    http://pastebin.com/yaBz4nHe
    And i got a problem with assigning the db result to smarty array:
    http://pastebin.com/V1FBhYNG

    If You can figure out a way for me to do this, I would appreciate it soo much.
    Regards,
    Sim00n.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s