contact

or cancel

A GUIDE to Simple Code Igniter Models

After a lot database code, you realize that the majority of your methods take on the same structure. For a while now, I have started all of our Code Igniter models with five generic methods to interact with the database, and they usually cover a good amount of any basic application’s needs. I am going to flip the CRUD acronym on end and use my own: GUIDE- standing for Get, Update, Insert, Delete, and Explicit.

5 Methods, 5 Lines

Let’s start with the core of what we are talking about, and the five lines of code (methods) that spell out GUIDE.

 function get($a,$b=array(),$c=0){$d=$this->db->get_where($a,$b);$e=$d->result_array();if($c)return $e[0];return $e;}

function update($a,$b=array(),$c){$this->db->update($a,$c,$b);return $this->db->affected_rows();}

function insert($a,$b){$this->db->insert($a,$b);return $this->db->insert_id();}

function delete($a,$b=array()){$this->db->delete($a,$b);return $this->db->affected_rows();}

function explicit($a){$b=$this->db->query($a);if(is_object($b))return $b->result_array();return $b;}

You notice we minified those methods, because if we are happy with them time after time, why should they take up pixel real-estate on our screens? Let’s start with the GET method, and examine it un-minified:

function get($table,$where=array(),$single=FALSE) {
  $q = $this->db->get_where($table,$where);
  $result = $q->result_array();
  if($single) {
    return $result[0];
  }
  return $result;
}

The real only explanation is the $single option in the function. Suppose you know you will only be getting one result back, maybe you specify a user ID in the $where array (see examples below). If this option is evaluated as true, the returned data array will be a single dimension. Essentially, if you are going to run the result data through a loop, you want a multidimensional array; if you the result as a simple array, use the single option.

The next three methods, Insert, Update, and Delete, just provide direct access to Code Igniters already-established active record tools, with return values that might be helpful in our application. You can refer to their use on the Code Igniter Active Record Class page.

function insert($table,$data) {
  $this->db->insert($table,$data);
  return $this->db->insert_id();
}

function update($table,$where=array(),$data) {
  $this->db->update($table,$data,$where);
  return $this->db->affected_rows();
}

function delete($table,$where=array()) {
  $this->db->delete($table,$where);
  return $this->db->affected_rows();
}

The final method is named Explicit, and is for explicit queries. The only added logic is detection of an object on the query result. If the result is an object, the function returns a result array, and otherwise, it returns the raw query result (likely a boolean-compatible value).

function explicit($query) {
  $q = $this->db->query($query);
  if(is_object($q)) {
    return $q->result_array();
  } else {
    return $q;
  }
}

Basic Usage

If you are not that familiar with Code Igniter, remember that it uses a fairly strict MVC architecture when it comes to the separation of controllers and models. Because of this you will want to place these methods inside a file in your model’s folder, perhaps “fav_model.php”. From your controller, you would call these methods like this:

//get all users in the users table
$users = $this->fav_model->get('users');

//get the user with an ID=5 from the users table, return a single array
$user = $this->fav_model->get('users',array('id'=>5),TRUE);

//update the users table with new data for user with ID=5
$data = array(
  'middle_name'=>'Henry',
  'birthday'=>'946684800'
);
$affected_rows = $this->fav_model->update('users',array('id'=>5),$data);

//insert new user into the users table
$data = array(
  'first_name'=>'Matt',
  'last_name'=>'Gaidica',
  'password'=>md5('abc123')
  'created'=>time()
);
$id = $this->fav_model->insert('users',$data);

//delete user ID=5 from table users
$affected_rows = $this->fav_model->delete('users',array('id'=>5));

//get all the information about user with ID=5 from users table
$data = $this->fav_model->explicit('SELECT * FROM users WHERE id=5');

Limitations and Bewares

There are some instances where these methods will not work, and where they might be outright dangerous to use. Here is a short list of just some instances that come to mind:

  • Your table names might change. If you use the table name as a variable in your model, and then change the table name inside the database, you will have to redo all those calls in your controllers. The alternative is to create a new method in your model for every table you are manipulating, so if it changes, you only rewrite the table name once.
  • You want to sort the data, or get really specific. Unless you are using the Explicit method, there is no ordering beyond the default database behavior, and no limits or offsets to the data returned. Well-planned queries are important when dealing with large data sets, or highly-efficient applications.
  • You want readable model methods. Creating one-fits-all code is sometimes counter-productive, and while the end result may work, it is hard for other developers (or on-lookers) to understand. A scaleable application is written so it makes sense to you and your team, even a year after writing it.

Thats All Folks

This is an easy breezy way to start out your model, and when things get more complicated, you can expand on the methods used in this GUIDE. Hope you learned something new, any questions or comments are welcome.

Comments