Showing posts with label models in codeigniter. Show all posts
Showing posts with label models in codeigniter. Show all posts

Sunday, January 28, 2018

Models in Codeigniter ...... MVC pattern !!

As we discussed in the previous post that codeigniter works on the MVC pattern, which is Models, Views and Controllers.
We have discussed in detail about the controllers and the Views in previous posts. Now we are going to discuss about the Models.

Firstly, a question arises here that

What are Models?

Models are most important part of MVC pattern. Models in codeigniter are extended for the parent class of CI_Models. Models are used to write queries in codeigniter. Models directly relates with databases. This parent class CI_Models provides a by default object which is "db". This object is used to access different database operations like select, insert, delete etc. e.g

$this->db->select('myTable');
$this->db->insert('myTable');
$this->db->delete('myTable');

How to create a model?

Models are created simply by creating new file in the Model folder which resides in the application folder of codeigniter and saving that file with .php extention. Keep the first letter of the model name capital. e.g MyModel.php

Every model has a some functions which are called through the accessing the model first and then accessing that function define and declared on the Models.

Every model is loaded first in the controllers, after loading the models, then its function are accessed in that controller.

How to define and declare model?

The code for declaring the model will be something like this. First you have to extend the parent class and create a user defined model class, by giving the same name to the class as you have given the name to file while creating the file in models folder.

The code in the file would be like the one given below:

<?php
class MyModel extends CI_Models{
public function exampleModel(){

echo "hello I am a model";

}
}
?>

 How to load a model in a Controller?

To make the model work and accessed through a controller. we need to load the model first. e.g we have created the model above with the name MyModel.php. Now how we will load this model in the controller that we created in the previous post , here is an example .

<?php class MyController extends CI_Controller {

public function index(){

$this->load->model('MyModel');    //No need to give the extention of model
$this->MyModel->exampleModel();  //function of Model that we created above

}
}
?>
This is how we load the model in controller and access the function of models.
I hope this post was a help for you . leave your queries in the comments. God bless you all !