How MVC works in Codeignitor ?
Codeignitor is based on MVC design pattern. We will see how the controller, model, and view work and display the result to the user.
Controller: Like the name suggest, it controls the communication between views and models. All the URL works in CodeIgniter with controller name. Now let’s see some point which we need to keep in mind when we create a new controller.
- When we create a class in a controller the name of the class should match with the file name and it should start with upper case else we will receive an error while running our project.
- Once the class is declared we inherit all the properties of CI_Controller with extends keywords to use all the properties of CI_Controller(Go through the PHP | Common terminology in OOP to understand inheritance). There won’t be any issue if we won’t extend CI_Controller but in that case, we won’t be able to access any property of CI_Controller.
- Every controller has a default function index which runs automatically when we define only controller name in URL. For the rest of the functions, we need to mention it manually after controller name in URL.
Model: Model is responsible to handle the queries related with backend. All the queries or functionalities of the backend like database, APIs we write in models. Now let’s see some point which we need to keep in mind when we create a new model.
- When we create a class in a model the name of the class should match with the file name and it should start with upper case else we will receive an error while running our project.
- Once the class is declared we inherit all the properties of CI_Model with extends keywords to use all the properties of CI_Model
- When we create a function in model make sure it should be public else it won’t be accessible in controller.
- To access the model in a controller it need to be loaded first, after loading the model we can call the function of that specific model in controller. Below is the line to load the model in a controller.
Below is the line to load model in autoload.php which is available in config folder . If we need the model globally in our project, then use autoload.php.
$autoload['model'] = array('post_model');
Keeping all the above point in mind we will see an example of how MVC works in CI.
Controller File: Create a file users.php in Controller folder and write down the code below.
Model File: Create a file usermodel.php in Model folder and write down the code below.
View File: Create a file users_list.php in View folder and write down the code below.
Now run http://localhost/ci_tutorial/index.php/Users in the browser.
Please Login to comment...