Model
What is a Model?

Models is Class that inherit CI_Model. When we are work with database like insert record,update record etc. so we create function in Model class and call from controller.We save Model classes in application/models/ folder. Model class name and model page name should be same like controller and class name and page name should be start with capital letter

you can not directly access model, you can run only from controller. You can see by default there is no any model.

How to create Model

Create this class file and save this application->models, And name of class name and page name should be same and start with capital letter.

<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class User_Model extends CI_Model {

public function  __construct(){

parent::__construct();

}

public function showuser(){

echo "This is show user function";
}

}

How to access Model.

We call model from controller. 

<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class User extends CI_Controller {

public function index()
{
$this->load->model('user_model');
$this->user_model->showuser();
}

}

Here we load and call model from user controller

For load model :  $this->load->model('user_model');  

For access model : $this->user_model->showuser();

Access Model by alias name

We call model from controller. 

<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class User extends CI_Controller {

public function index()
{
$this->load->model('user_model','user');
$this->user->showuser();
}

}

Note : In the above code we create model alias name user, so codeigniter create user object. It will not create user_model.

Load Model in Full Application

Sometime we need model class in full application, we don't load model in controller, we declare in autoload.php file that is located in application->config->autoload.php

So first open this file then you can see
$autoload['model'] = array();

Now you can provide your own model here like

$autoload['model'] = array('test1_model', 'test2_model');


Previous
Next