Model instances with Active Record on CodeIgniter

Recently we developed at CodeKings a customized CMS to meet specific needs for a client. One of the requirements of this project was that we had to use the CodeIgniter MVC framework. Early in the programming, we feel the need to access methods of model’s objects to navigate the hierarchy of classes. Thus, in a control, for example, we could do this:

$user = $this->User_model->get_by_email('');
$group = $user->get_group();
echo $group->name; // Prints the name of the group the user belongs.

The problem is that in CodeIgniter, after calling the get method of Active Record class the value returned when generating query results is an array of StdClass’ instances (or an empty array on failure). In our case, it would be better to have a list of User_model. So, at first, we wrote the following helper (data_helper) to assist our work:

if (!function_exists('import_data')) {

  function import_data(&$object, $data)
    if (is_object($data)) {
      $data = get_object_vars($data);
    if (is_array($data)) {
      foreach ($data as $property => $value) {
        if (property_exists($object, $property)) {
          $object->$property = $value;
    return $object;


Done! Now we can write our model class as follows:

class User_model extends Model

  const TABLE_NAME = 'user';

  public $id;
  public $group;
  public $name;
  public $email;
  public $password;

  protected $_group;

  function User_model($data = array())
    import_data($this, $data);

  function insert()
    return $this->db->insert(self::TABLE_NAME, $this);

  /* [...] */

  function get_all()
    $query = $this->db->get(self::TABLE_NAME);
    $result = array();
    foreach ($query->result() as $data) {
      $result[] = new self($data);
    return $result;

  function get_by_email($email)
    $user = null;
    $query = $this->db->get_where(self::TABLE_NAME, array('email' => $email));
    return $query->num_rows() > 0 ? new self(array_shift($query->result())) : null;

  /* [...] */

  function get_group()
    if (!isset($this->_group)) {
      $CI = & get_instance();
      $this->_group = $CI->Group_model->get_by_id($this->group);
    return $this->_group;


This approach is very useful when you need access to methods of model’s instances combined with the use of Active Record class.


One thought on “Model instances with Active Record on CodeIgniter

Leave a Reply

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

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

Google+ photo

You are commenting using your Google+ 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

This site uses Akismet to reduce spam. Learn how your comment data is processed.