- Models¶
- What is a Model?¶
- Anatomy of a Model¶
- Loading a Model¶
- Auto-loading Models¶
- Connecting to your Database¶
- Models¶
- What is a Model?¶
- Anatomy of a Model¶
- Loading a Model¶
- Auto-loading Models¶
- Connecting to your Database¶
- How to Create and Load Model in CodeIgniter
- Contents
- 1. Load Database
- 2. Create Model
- 3. Controller
- 4. Conclusion
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 CodeIgniter 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 Blog_model extends CI_Model public $title; public $content; public $date; public function get_last_ten_entries() $query = $this->db->get('entries', 10); return $query->result(); > public function insert_entry() $this->title = $_POST['title']; // please read the below note $this->content = $_POST['content']; $this->date = time(); $this->db->insert('entries', $this); > public function update_entry() $this->title = $_POST['title']; $this->content = $_POST['content']; $this->date = time(); $this->db->update('entries', $this, array('id' => $_POST['id'])); > >
The methods in the above example use the Query Builder database methods.
For the sake of simplicity in this example we’re using $_POST directly. This is generally bad practice, and a more common approach would be to use the Input Library $this->input->post(‘title’) .
Anatomy of a Model¶
Model classes are stored in your application/models/ directory. They can be nested within sub-directories if you want this type of organization.
The basic prototype for a model class is this:
class Model_name extends CI_Model >
Where Model_name is the name of your class. Class names must have the first letter capitalized with the rest of the name lowercase. Make sure your class extends the base Model class.
The file name must match the class name. For example, if this is your class:
class User_model extends CI_Model >
application/models/User_model.php
Loading a Model¶
Your models will typically be loaded and called from within your controller methods. To load a model you will use the following method:
If your model is located in a sub-directory, include the relative path from your models directory. For example, if you have a model located at application/models/blog/Queries.php you’ll load it using:
Once loaded, you will access your model methods using an object with the same name as your class:
$this->load->model('model_name'); $this->model_name->method();
If you would like your model assigned to a different object name you can specify it via the second parameter of the loading method:
$this->load->model('model_name', 'foobar'); $this->foobar->method();
Here is an example of a controller, that loads a model, then serves a view:
class Blog_controller extends CI_Controller public function blog() $this->load->model('blog'); $data['query'] = $this->blog->get_last_ten_entries(); $this->load->view('blog', $data); > >
Auto-loading Models¶
If you find that you need a particular model globally throughout your application, you can tell CodeIgniter to auto-load it during system initialization. This is done by opening the application/config/autoload.php file and adding the model to the autoload array.
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:
- You can connect using the standard database methods described here , either from within your Controller class or your Model class.
- You can tell the model loading method to auto-connect by passing TRUE (boolean) via the third parameter, and connectivity settings, as defined in your database config file will be used:
$this->load->model('model_name', '', TRUE);
$config['hostname'] = 'localhost'; $config['username'] = 'myusername'; $config['password'] = 'mypassword'; $config['database'] = 'mydatabase'; $config['dbdriver'] = 'mysqli'; $config['dbprefix'] = ''; $config['pconnect'] = FALSE; $config['db_debug'] = TRUE; $this->load->model('model_name', '', $config);
© Copyright 2019 — 2022, CodeIgniter Foundation. Last updated on Mar 03, 2022.
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 CodeIgniter 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 Blog_model extends CI_Model public $title; public $content; public $date; public function get_last_ten_entries() $query = $this->db->get('entries', 10); return $query->result(); > public function insert_entry() $this->title = $_POST['title']; // please read the below note $this->content = $_POST['content']; $this->date = time(); $this->db->insert('entries', $this); > public function update_entry() $this->title = $_POST['title']; $this->content = $_POST['content']; $this->date = time(); $this->db->update('entries', $this, array('id' => $_POST['id'])); > >
The methods in the above example use the Query Builder database methods.
For the sake of simplicity in this example we’re using $_POST directly. This is generally bad practice, and a more common approach would be to use the Input Library $this->input->post(‘title’) .
Anatomy of a Model¶
Model classes are stored in your application/models/ directory. They can be nested within sub-directories if you want this type of organization.
The basic prototype for a model class is this:
class Model_name extends CI_Model >
Where Model_name is the name of your class. Class names must have the first letter capitalized with the rest of the name lowercase. Make sure your class extends the base Model class.
The file name must match the class name. For example, if this is your class:
class User_model extends CI_Model >
application/models/User_model.php
Loading a Model¶
Your models will typically be loaded and called from within your controller methods. To load a model you will use the following method:
If your model is located in a sub-directory, include the relative path from your models directory. For example, if you have a model located at application/models/blog/Queries.php you’ll load it using:
Once loaded, you will access your model methods using an object with the same name as your class:
$this->load->model('model_name'); $this->model_name->method();
If you would like your model assigned to a different object name you can specify it via the second parameter of the loading method:
$this->load->model('model_name', 'foobar'); $this->foobar->method();
Here is an example of a controller, that loads a model, then serves a view:
class Blog_controller extends CI_Controller public function blog() $this->load->model('blog'); $data['query'] = $this->blog->get_last_ten_entries(); $this->load->view('blog', $data); > >
Auto-loading Models¶
If you find that you need a particular model globally throughout your application, you can tell CodeIgniter to auto-load it during system initialization. This is done by opening the application/config/autoload.php file and adding the model to the autoload array.
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:
- You can connect using the standard database methods described here , either from within your Controller class or your Model class.
- You can tell the model loading method to auto-connect by passing TRUE (boolean) via the third parameter, and connectivity settings, as defined in your database config file will be used:
$this->load->model('model_name', '', TRUE);
$config['hostname'] = 'localhost'; $config['username'] = 'myusername'; $config['password'] = 'mypassword'; $config['database'] = 'mydatabase'; $config['dbdriver'] = 'mysqli'; $config['dbprefix'] = ''; $config['pconnect'] = FALSE; $config['db_debug'] = TRUE; $this->load->model('model_name', '', $config);
© Copyright 2019 — 2022, CodeIgniter Foundation. Last updated on Mar 03, 2022.
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
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
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
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.
If you found this tutorial helpful then don’t forget to share.