Chris Nizzardini

Salt Lake City, Utah Developer / Human / Blogger

Reducing Code using CodeIgniters Active Record Class

UPDATE Nov. 9, 2011: I have begun moving away from using this in my code. I am now using a core Model class that is extended by other models that takes care of stuff like this. Please read Inheritance in CodeIgniter: Adding More Functionality To Your Models for more information. While this is still an okay solution it becomes a bitch to remember to unset variables as your classes grow.

This is a quick blog post on some stuff I’ve discovered using CodeIgniters Active Record Class. I’ve found two ways to reduce the amount of code I’m writing.

Simplifying Inserts and Updates:

Since I am new to CodeIgniter I began writing my insert and update statements as follows:

$data = array(
    'tech_id' => $this->tech_id,
    'note_date' => date('Y-m-d'),
    'tech_note' => $this->tech_note,
    'year' => $this->year,
    'model_id' => $this->model_id,
    'is_global' => $this->is_global,
    'auto_glass_part_type_id' => NULL
);
$this->db->insert('tbl_something',$data);

I knew this was bad cause I was doing a bunch of CRUD code that was taking my time away from REAL programming. If you’re using good OOP design patterns you can simplify this:

$data = get_object_vars($this);
$this->db->insert('tbl_something',$data);

Anything that you don’t want included in the insert/update can simply be unset() from the $data array.

Make Query Methods a Swiss Army Knife

Another problem I had in my code I was using multiple methods in model that were doing database calls. These methods were all selecting the same data, they just had different WHERE parameters. So if you have the following code:

public function getAll(){
  $this->db->select('tbl_lead.*, disposition, auto_make.make as make, auto_model.model as model');
  $this->db->where('tbl_lead.shop_id',$this->session->userdata('shop_id'));
  return $this->db->get($this->table_name);
}

You can simplify it as follows:

public function getAll($dbObj=''){
  $this->db->select('tbl_lead.*, disposition, auto_make.make as make, auto_model.model as model');
  if(is_object($dbObj)){
      $this->db = $dbObj;
  }
  return $this->db->get($this->table_name);
}

Now we have a single method that returns everything you need, but gives you the option of passing custom WHERE parameters.

Chris Nizzardini has been developing web applications since 2006. He lives and works in beautiful Salt Lake City, Utah. If you’re interested in hiring me for contract work please visit IO Spring LLC.

Twitter Google+ 

,

2 thoughts on “Reducing Code using CodeIgniters Active Record Class

Leave a Reply

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

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>