Simple MY_Model class for all models in Codeigniter

No Comments

Codeigniter’s model structure is a bit complicated and doesn’t quite work in the ways you would think it should.

However, I have extended the default model class to include some helpful functions which should be available to all models. It is by far the easiest and most comfortable way to use models in Codeigniter that I’ve found so far.

Here is the code. Feel free to extend and edit as you feel. Let me know how you get on.

Put this in application/core/MY_Model.php

<?php
 
class MY_Model extends CI_Model {
 
	protected $table;
	public $obj;
 
	function __construct(){
		parent::__construct();
	}
 
        // insert a row - pass in an object to $o and it will insert
	public function insert($o){
		$this->db->insert($this->table, $o);
		$id = $this->db->insert_id();
 
		$query = $this->db->where($this->table.".id", $id)->get($this->table);
		$this->obj = $query->row();
	}
 
        // update - set the model's obj variable to be the updated object
        // then run this function. Assumes your primary key column is id
	public function update(){
		$this->db->update($this->table, $this->obj, array("id"=>$this->obj->id));
	}
 
        // get all the records with where clause if necessary
        // returns array of objects
	public function get_all($where = false){
		if($where){
			$this->db->where($where);
		}
		$query = $this->db->get($this->table);
		return $query->result();
	}
 
        // get a single record with where clause if necessary
        // returns object
	public function get($where = false){
		if($where){
			$this->db->where($where);
		}
		$query = $this->db->get($this->table, 1);
		return $query->row();
	}
 
}

Now you can extend and set the $table variable in your constructor.

class Table_model extends MY_Model {
    public function __construct(){
        parent::__construct();
 
        $this->table = "tblTable";
    }
}

This means you get all the default get(), get_all() and insert, update functions out of the box, with no need to replicate code.

Twitter