Code Igniter User Guide Version 1.4.0


Models

Models are optionally available for those who want to use a more traditional MVC approach.

What is a Model?

Models are PHP classes that are designed to work with information in your database. For example, let's say you use Code Igniter to manage a blog. You might have a model class that contains functions to insert, update, and retrieve your blog data. Here is an example of what such a model class might look like:

class Blogmodel extends Model {

    var $title   = '';
    var $content = '';
    var $date    = '';

    function Blogmodel()
    {
        // Call the Model constructor
        parent::Model();
    }
    
    function get_last_ten_entries()
    {
        $query = $this->db->get('entries', 10);
        return $query->result();
    }

    function insert_entry()
    {
        $this->title   = $_POST['title'];
        $this->content = $_POST['content'];
        $this->date    = time();

        $this->db->insert('entries', $this);
    }

    function update_entry()
    {
        $this->title   = $_POST['title'];
        $this->content = $_POST['content'];
        $this->date    = time();

        $this->db->update('entries', $this, array('id', $_POST['id']));
    }

}

Note: The functions in the above example use the Active Record database functions.

Anatomy of a Model

Model classes are stored in your application/models/ folder. The basic prototype for a model is this:

class Model_name extends Model {

    function Model_name()
    {
        parent::Model();
    }
}

Where Model_name is the name of your class. Class names must be capitalized. Make sure your class extends the base Model class.

The file name will be a lower case version of your class name. For example, if your class is this:

class User_model extends Model {

    function User_model()
    {
        parent::Model();
    }
}

Your file will be this:

application/models/user_model.php

Loading a Model

Your models will typically be loaded and called from within your controller functions. To load a model you will use the following function:

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

Once loaded, you will access your model functions using an object with the same name as your class:

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

$this->Model_name->function();

If you would like your model assigned to a different object name you can specify it via the second parameter of the loading function:

$this->load->model('Model_name', 'fubar');

$this->fubar->function();

Here is an example of a controller, that loads a model, then serves a view:

class Blog_controller extends Controller {

    function blog()
    {
        $this->load->model('Blog');

        $data['query'] = $this->Blog->get_last_ten_entries();

        $this->load->view('blog', $data);
    }
}

Connecting to your Database

When a model is loaded it does NOT connect automatically to your database. The following options for connecting are available to you: