Defining a Model Class for Handling Views with CodeIgniter - Handling database contents with a simple model class (
Page 3 of 4 )
In the preceding segment, I mentioned that it was perfectly possible to incorporate a model class to access database contents, instead of directly using the database class included with CodeIgniter. So, to put this theoretical concept into practice, below I created such a class. In this case, it is charged with fetching some rows from the “users” MySQL table that you learned before, and with counting its records as well.
In summary, this model class, called “User_model,” is defined in the following way:
<?php
class User_model extends Model{
function User_model(){
// call the Model constructor
parent::Model();
// load database class and connect to MySQL
$this->load->database();
}
// fetch all users
function getAll(){
$query=$this->db->get('users');
// return result set as object
return $query->result();
}
// fetch some users based on a predefined condition
function getWhere($field,$param){
$this->db->where($field,$param);
$query=$this->db->get('users');
// return result set as object
return $query->result();
}
// get total number of users
function getNumber(){
return $this->db->count_all('users');
}
}
?>
In reality, understanding how the above “User_model” class works is a pretty straightforward process, don’t you think? As you can see, this model implements a few basic methods for retrieving users from the corresponding database table, and for counting them as well. Naturally, it’s feasible to aggregate more methods that perform inserts, updates and deletions, but for now I’ll keep the signature of the model simple.
So far, so good. At this point, I showed you how to build a basic model class that will be responsible for fetching user-related data from the pertinent MySQL table. Therefore, the next step is to change the signature of the “WebPage” controller class so that it can use the model for accessing database contents.
This modification will be discussed in detail in the last section of this tutorial. Therefore, please click on the link below and read the upcoming segment.