Now that you know what a Model is and what it's used for, we can take a look at how to construct a Model.
Models are stored in system/application/models/
. The class of your model should have the first letter capitalized and the rest of the name lowercase, and also extend the base class of Model. The class should also have a constructor that calls upon the base class constructor, as seen in the next code example.
<?php class Mymodel extends Model { funcion Mymodel() { parent::Model(); } } ?>
The filename of this model should be an all-lowercase version of the name; the filename therefore will be mymodel.php
.
A model is loaded from Controller functions. Loading a model takes just one line of code.
$this->load->model('model_name');
In this instance, you should replace model_name
with the name of your model. If your model is located in a sub-folder, you would load the model as follows:
$this->load->model('sub_folder/model_name');
Once loaded, you access your model functions by using the global object with the same name as your model name.
$this->model_name->function_name();
You can assign a new name for your Model object by passing it to the second parameter of the loading function.
$this->load->model('model_name', 'different_name');
Now you would call your model functions as follows:
$this->different_name->function_name();
Here's an example of a controller calling a model and serving a view.
<?php class Shop extends Controller { function Shop() { parent::Controller(); } function index() { $this->load->model('products'); $products = $this->products->build_list(); $this->load->view('shop', $products); } } ?>
When a model is loaded, it does not connect to the database automatically unless you autoload the database class for your application. You can tell the model to connect to the database automatically by passing boolean TRUE
as the third parameter.
$this->load->model('model_name', '', TRUE);
The model will now connect to the database using the setting defined in your database.php
configuration file, which is located in system/application/config/
.
You can pass an array of configuration details to the third parameter if you wish to use a database other than the one that's set up in your database configuration file.
$config['hostname'] = "localhost"; $config['username'] = "myusername"; $config['password'] = "mypassword"; $config['database'] = "mydatabase"; $config['dbdriver'] = "mysql"; $config['dbprefix'] = ""; $config['pconnect'] = FALSE; $config['db_debug'] = TRUE; $this->load->model('model_name', '', $config);