Model classes are stored in 'application/models/' folder.
Gallery model example (stored in 'application/models/gallery_model.php'):
<?php
class Gallery_model extends CI_Model {
var $title = '';
var $content = '';
function __construct() {
parent::__construct();
}
function get_recent_entries() {
$query = $this->db->get('entries', 10);
return $query->result();
}
function insert_entry() {
$this->title = $this->input->post('title');
$this->content = $this->input->post('content');
$this->db->insert('entries', $this);
}
function update_entry() {
$this->title = $this->input->post('title');
$this->content = $this->input->post('content');
$this->db->update('entries', $this, array('id' => $this->input->post('id')));
}
}
?> |
<?php
class Gallery_model extends CI_Model {
var $title = '';
var $content = '';
function __construct() {
parent::__construct();
}
function get_recent_entries() {
$query = $this->db->get('entries', 10);
return $query->result();
}
function insert_entry() {
$this->title = $this->input->post('title');
$this->content = $this->input->post('content');
$this->db->insert('entries', $this);
}
function update_entry() {
$this->title = $this->input->post('title');
$this->content = $this->input->post('content');
$this->db->update('entries', $this, array('id' => $this->input->post('id')));
}
}
?>
Loading a Model
<?php
$this->load->model('Gallery_model');
$this->load->model('subfolder/Gallery_model'); // load model from 'application/models/subfolder/gallery_model.php'
$this->Gallery_model->get_recent_entries(); // access the model functions using an object with the same name as the model class
?> |
<?php
$this->load->model('Gallery_model');
$this->load->model('subfolder/Gallery_model'); // load model from 'application/models/subfolder/gallery_model.php'
$this->Gallery_model->get_recent_entries(); // access the model functions using an object with the same name as the model class
?>
Example of controller that loads model and serves view:
<?php
class Gallery extends CI_Controller {
function listing() {
$this->load->model('Gallery_model');
$data['query'] = $this->Gallery_model->get_recent_entries();
$this->load->view('template', $data);
}
}
?> |
<?php
class Gallery extends CI_Controller {
function listing() {
$this->load->model('Gallery_model');
$data['query'] = $this->Gallery_model->get_recent_entries();
$this->load->view('template', $data);
}
}
?>
Auto-loading models
You can set list of models which will be auto-loaded during system initialization in file: "application/config/autoload.php"