How to Create and Load Model in CodeIgniter
How to Create and Load Model in CodeIgniter
In CodeIgniter Model are the PHP classes where all database related manipulation is done e.g. fetching records, insert, update, and delete records.
Within this, all data processing logic is done.
All model files are managed in application/models
directory and they are load and access by the controller.
Contents
- Load Database
- Create Model
- Controller
- Conclusion
1. Load Database
First, need to load the database
library for performing any database related manipulation.
Navigate to application/config/database.php
and define Database connection.
$db['default'] = array(
'dsn' => '',
'hostname' => 'localhost',
'username' => 'root', // Username
'password' => '', // Password
'database' => 'tutorial', // Database name
'dbdriver' => 'mysqli',
'dbprefix' => '',
'pconnect' => FALSE,
'db_debug' => (ENVIRONMENT !== 'production'),
'cache_on' => FALSE,
'cachedir' => '',
'char_set' => 'utf8',
'dbcollat' => 'utf8_general_ci',
'swap_pre' => '',
'encrypt' => FALSE,
'compress' => FALSE,
'stricton' => FALSE,
'failover' => array(),
'save_queries' => TRUE
);
Load Database
Open application/config/autoload.php
and add the database
in libraries array()
.
$autoload['libraries'] = array("database");
Default controller
Open application/config/routes.php
and edit default_controller
value to User
.
$route['default_controller'] = 'User';
2. Create Model
Create a Main_model.php
file in application/models
directory.
Within the class create methods for data processing.
I have created a getUsers()
method to select all records from the users
table and return an Array response.
Completed Code
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Main_model extends CI_Model {
function getUsers(){
$response = array();
// Select record
$this->db->select('*');
$q = $this->db->get('users');
$response = $q->result_array();
return $response;
}
}
3. Controller
Model is load from the controller.
Here, is the syntax for loading Model and accessing methods.
Syntax (loading model) –
$this->load->model(Model-class-name);
Syntax (call model method) –
$this->[Model-class-name]->method-name();
Create a User.php
file in application/controllers
directory.
Load above created Main_model
using $this->load->model('Main_model')
method in the __construct()
method and call getUsers()
method using $this->Main_model->getUsers()
.
Store the return response in a $data
variable.
Completed Code
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class User extends CI_Controller {
public function __construct(){
parent::__construct();
// Load model
$this->load->model('Main_model');
}
public function users(){
// get data from model
$data = $this->Main_model->getUsers();
}
}
4. Conclusion
Manage all model files in application/models
directory and in the controller it is better to load the models from the __construct()
method if you want to use them in more than one method.