Sep 3 2011
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.
Evil Hackers from Outerspace Unscientific Benchmarking of Type Casting, is_numeric, and regex in PHP


You’ve got a good blog here, Chris. Thanks for sharing your insight on these assorted web development topics. I’ll keep an eye on it.
Thanks Simon.