A smart codeigniter model

Extending the Codeigniter Model class is fun and it is a great idea to reduce the code in your model classes by adding some smart functions to it.

Extending the Codeigniter Model class is a great idea to reduce the code in your model classes by adding some smart functions to it. After extending it, there is no need to write any code in your model for regular CRUD operations and Search functions. Instead only need to inherit from the new model class instead of CI Model class. The first step of doing this is creating a file in application/core folder with name "MY_model.php". Define the new model class in it by extending it from the Codeigniter Model class and define some variables as given below.


if ( ! defined('BASEPATH')) 
    exit('No direct script access allowed'); 

class MY_Model extends CI_Model 
{ 
    public $table; 
    public function __construct() 
    { 
        parent::__construct(); 
        $this->table = get_Class($this); 
        $this->load->database(); 
    } 
}

In the above part there is one variable called $table is defined and it is initialized with the class name. We will use the class name as the table name in our methods, when table name is not passed to the methods. We are going to have the methods for insert, update, search and save. The 'Save' method will be smarter one. Instead of inserting the record to the table it will check if there is any record already with the passed primary key value and will call an update operation instead of insert.


public function save($data,$tablename="") 
{ 
    if($tablename=="") 
    { 
        $tablename = $this->table; 
    } 
    $op = 'update'; 
    $keyExists = FALSE; 
    $fields = $this->db->field_data($tablename); 

    foreach ($fields as $field) 
    { 
        if($field->primary_key==1) 
        { 
            $keyExists = TRUE;
            if(isset($data[$field->name])) 
            { 
                $this->db->where($field->name, $data[$field->name]); 
            } 
            else 
            { 
                $op = 'insert'; 
            } 
        } 
    } 
    if($keyExists && $op=='update') 
    { 
        $this->db->set($data); 
        $this->db->update($tablename); 
        if($this->db->affected_rows()==1) 
        { 
            return $this->db->affected_rows(); 
        } 
    } 
    $this->db->insert($tablename,$data); 
    return $this->db->affected_rows(); 
} 

function search($conditions=NULL,$tablename="",$limit=500,$offset=0) 
{     
    if($tablename=="") 
    { 
        $tablename = $this->table; 
    } 
    if($conditions != NULL) 
        $this->db->where($conditions); 

    $query = $this->db->get($tablename,$limit,$offset=0); 
    return $query->result(); 
} 

function insert($data,$tablename="") 
{ 
    if($tablename=="") 
        $tablename = $this->table; 
    $this->db->insert($tablename,$data); 
    return $this->db->affected_rows(); 
} 

function update($data,$conditions,$tablename="") 
{ 
    if($tablename=="") 
        $tablename = $this->table; $this->db->where($conditions); 
    $this->db->update($tablename,$data); 
    return $this->db->affected_rows(); 
} 

function delete($conditions,$tablename="") 
{ 
    if($tablename=="") 
        $tablename = $this->table; 
    $this->db->where($conditions); 
    $this->db->delete($tablename); 
    return $this->db->affected_rows(); 
}

How to use this Model?

Create a model by inheriting it from the model class created above and call the functions. Below is an example class and described the usage below the coding.


if ( ! defined('BASEPATH')) 
    exit('No direct script access allowed'); 
class Samlpe extends MY_Model 
{ 
    public function __construct() 
    { 
        parent::__construct(); 
    } 
}

We have defined the Model class without any methods in it, and see below how we can use it in a controller.


$this->load->model("Sample"); 
$condition['id'] = '1'; 
$this->sample->delete($condition); //Delete from Sample table, if same as class name then no need to pass table name 
$this->sample->delete($condition,"AnotherTable"); //If delete from some other table 
$data['fieldName'] = 'field value'; 
$data['fieldName2'] = 'field value 2'
$this->sample->save($data); 

Share your opinion on this and any ideas for improvements on this?

Website in minutes

Do you know that you can generate a complete PHP websites in minutes with PHP Website Generator?

Features

  • Free admin dashboard
  • Role based security
  • Login with Facebook, Google and more
  • Queue based email processing
  • Price at $3 for website
  • Uses CodeIgniter framework

Generate website now See Pricing



Connect with Google or Facebook and generate your next CodeIgniter website in minutes with plenty of features like searching with pagination, AJAX based grid data editors, group based security and admin portal etc.