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