Codeigniter Models

Home > Codeigniter Tutorial > Codeigniter Models



Models

Models are the classes designed to work with information in the database. For example, if we are using CodeIgniter to manage users in our application then we must have model class, which contains functions to insert, update, display and delete data.

Creating Model Class

Syntax

<?php 
   class Model_name extends CI_Model 
   { 
      public function __construct()
	  { 
         parent::__construct(); 
      } 
   } 
?>

Note : Model Classes always stored inside Applicaion/models directory. Model Class name must be started with Capital Letters(or use camel case). Class name and Page name must be similar. Each Model class inherit Codeigniter's CI_Model Class .

Create a user's Model Class

<?php 
   class UserModel extends CI_Model 
   { 
      public function __construct()
	  { 
         parent::__construct(); 
      } 
   } 
?>

Here we have created a model class UserModel. UserModel Class must be saved inside Application/modesl/UserModel.php

Loading Model

Every Model class called/used inside a Controller. To call a model class inside controller following code can be used

$this->load->model('model_name');

After loading model class inside Controller we can use other methods of Model Class Syntax

$this->model_name->method_name();