MVC is an approach or method to manage a web application or software development process in three layers that have their own functionality, so that the project will be made in a more managed and distributed manner. Here distributed in the sense that the three layers Model, View, Controller can be given to individual team members.

MVC

These three components are:

  1. Model: It contains the information about the data in the form of SQL queries manes database part.

  2. View: It is the front part that is viewed by the client and is mainly coded in a web application using a language like HTML, CSS, jQuery and so on.

  3. Controller: This provides the entire control of a project. Like if a link was clicked then what should be done next or what event will take effect. Here if more than one request are on the same page for the same controller then we will use a switch case statement to differentiate these operations.
    See this entire process with an example on a PHP project that has a login, signup and user profile operation are done.

The Directory Structure will be look like this:

MVC project

In the preceding figure mvc_project is the project name. There are three folders that it contains, Controller, Model and View. These have their own separate PHP file that has specific tasks. There are two files, config.php and index.php, that are used by every file.

Index.php code

  1. <?php
  2. require_once 'Controller/userController.php';
  3. $controller = new userController();
  4. $controller->handleRequest();
  5. ?>

The following describes how to run the process:

  1. index.php is executed.

  2. Because there no operation is provided, in index.php, in the call of the userController.php file's handleRequest method, op=null so we include homepage.php in this file.

  3. When a login or submit button is provided the corresponding operation will be executed and can be seen in the browser URL that is evaluated By $_GET[‘op’] in the userController.php file and the corresponding operation is execuded.

Points to be noted:

  1. All controlling code should be contained in the controller file.

  2. Every table in the database has a different model file like loginmodel.php.

  3. All possible quires to that table will be in it's corresponding model.

  4. To control various entities, like user related operations, each can have a different controller file.

  5. If the project contains an admin Control Panel then it is treated as a different project, all files will be made different from the user client. The directory structure can be like in these types of project:

    Folder

  6. If a session is maintained then it will always begin at the first line of the controller file.

Summary

In this article we see how to implement MVC directory structure in PHP and got to know how it is managed using PHP5 with it's OOP approach.