CodeIgniter – Extending CI_Model

Today I would like to discuss about CodeIgniter (CI) models and how you can achieve code reuse by “overriding” the base CI_Model class.

First let’s take a simple example where you have two models in your application : employee, employee_leave

You would normally create two classes :
[php]
class Employee extends CI_Model {

public function get_by_id($id)
{
//some repository operation
}

}

class Employee_Leave extends CI_Model {

public function get_by_employee_id($id)
{
//some repository operation
}

}
[/php]

which is fine, and in your controller if you need to get an employee by id you would do something like :
[php]
$this->employee->get_by_id(/* id of your employee*/);
[/php]

same for your employee leave
[php]
$this->employee_leave->get_by_employee_id(/* id of your employee*/);
[/php]

The implementation of get_by_id and get_by_employee_id would be a SELECT query to the underlying data source. Using Active Record class, it would be  :
[php]
$query = $this->db->get_where(’employee’, array(‘id’ => $id), $limit, $offset);
[/php]
and
[php]
$query = $this->db->get_where(’employee_leave’, array(’employee_id’ => $employee_id), $limit, $offset);
[/php]
A more elegant way to work out the same operation would be by overriding the base CI_Model and adding generic functions.
[php]

class MY_Model extends CI_Model {

// will hold the table name of the current instance
var $tablename = “”;

// this constructor will help us initialize our child classes
public function __construct($tablename)
{
$this->tablename = $tablename;
parent::__construct();
}

public function get_all($limit = -1, $offset = 0, $orderby = ”) {}

public function get_total_count() {}

public function get_total_count_where($where) {}

public function get_where($where = array(), $limit = 10, $offset = 0, $orderby = ”) {}

}
[/php]

By building building this custom Model with an overloaded constructor that will take the table name as parameter, you will be simplifying the child classes build on top.

You need to modify your current Model (employee and employee_leave) to make use of your new base Model.

[php]
class Employee extends MY_Model {

public function __construct()
{
parent::__construct(’employee’);
}

}

class Employee_Leave extends MY_Model {

public function __construct()
{
parent::__construct(’employee_leave’);
}

}
[/php]

 

In you controller the code will now be :

[php]
$this->employee->get_where(/* where condition with id of your employee*/);
[/php]

same for your employee leave
[php]
$this->employee_leave->get_where(/* where condition with id of your employee*/);
[/php]

 

A very basic example that can be extended to build some solid and complex logic around your Model so that you don’t repeat the same code for performing repository operation.

2 comments on “CodeIgniter – Extending CI_Model

Leave a Reply

Your email address will not be published. Required fields are marked *