A Simplified Approach to MVC on PHP

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.       
  4.     $controller = new userController();  
  5.       
  6.     $controller->handleRequest();  
  7. ?>   
  • index.php file is the default file, in other words if we run this file locally on the local server by writing url:localhost/mvc_project then index.php is called automatically.

  • In this file we require userController.php to access it's properties. Make it's object and call the userController file method in which a different operation will be handeled.

    Config.php code
    1. <?php  
    2.   
    3. /** 
    4.  *  
    5.  */  
    6. class Config  {  
    7.       
    8.     function __construct() {  
    9.         $this->localhost = "localhost";  
    10.         $this->username  = "root";  
    11.         $this->password = "sandeep";  
    12.         $this->database = "mvc";  
    13.     }  
    14. }  
    15.   
    16.   
    17. ?>  
  • Config.php is the configuration file. It's class constructor is used and all the properties of the connection string are defined. I use MySQLi for this.

    loginModel.php code snippet
    1. <?php  
    2.   
    3. class loginmodel  
    4. {  
    5.     function __construct($host,$uname,$pass,$db)  
    6.     {  
    7.         $this->localhost = $host;  
    8.         $this->username = $uname;  
    9.         $this->password =  $pass;  
    10.         $this->database = $db;  
    11.                               
    12.     }  
    13.       
    14.     public function openDb()  
    15.     {  
    16.         $this->conn=new mysqli($this->localhost,$this->username,$this->password,$this->database);  
    17.         if ($this->conn->connect_error)   
    18.         {  
    19.             die("Connection failed: " . $this->conn->connect_error);  
    20.         }  
    21.     }  
    22.       
    23.     public function closeDb()  
    24.     {  
    25.         $this->conn->close();  
    26.     }  
    27.       
    28.     public function login($name,$password)  
    29.     {  
    30.         $this->openDb();  
    31.         $stmt=$this->conn->prepare("SELECT * FROM usertbl where name=? and password=?");  
    32.         $stmt->bind_param("ss",$name,$password);  
    33.         $stmt->execute();  
    34.         $res=$stmt->get_result();  
    35.         $stmt->close();  
    36.         $this->closeDb();  
    37.         return $res->fetch_object();  
    38.     }  
    39.       
    40.     public function signup($name,$password,$address)  
    41.     {  
    42.         try  
    43.         {     
    44.             $this->openDb();  
    45.             $stmt=$this->conn->prepare("INSERT INTO USERTBL (name,password,address) VALUES (?, ?, ?)");  
    46.             $stmt->bind_param("sss"$name,$password,$address);  
    47.             $stmt->execute();  
    48.             $res$stmt->get_result();  
    49.             $last_id=$this->conn->insert_id;  
    50.             $stmt->close();  
    51.             $this->closeDb();  
    52.             return $last_id;  
    53.         }  
    54.         catch (Exception $e)   
    55.         {  
    56.             $this->closeDb();  
    57.             throw $e;  
    58.         }  
    59.     }  
    60.       
    61.     public function selectUserById($userid)  
    62.     {  
    63.         try  
    64.         {  
    65.             $this->openDb();  
    66.             $stmt=$this->conn->prepare("SELECT * FROM USERTBL WHERE id=?");  
    67.             $stmt->bind_param("i",$userid);  
    68.             $stmt->execute();  
    69.             $res=$stmt->get_result();  
    70.             $stmt->close();  
    71.             $this->closeDb();  
    72.             return $res->fetch_object();   
    73.         }  
    74.         catch(Exception $e)  
    75.         {  
    76.             $this->closeDb();  
    77.             throw $e;     
    78.         }  
    79.           
    80.     }  
    81. }  
    82.   
    83. >  
  • In this file I use a prepared statement of MySQLi to prevent SQL injection attacks.

  • Bind_param is bindin of the parameter.

    userController.php code snippet
    1. <?php  
    2. session_start();  
    3.     require 'Model/loginModel.php';//include loginmodel.php file to access it’s property.  
    4.     require_once 'config.php';//include config.php.  
    5.   
    6.     class userController   
    7.     {  
    8.         function __construct()   
    9.         {  
    10.             $this->conset = new Config();//make config file object to make connection string.  
    11.             $this->userobj =  new loginModel($this->conset->localhost,$this->conset->username,$this->conset->password,$this->conset->database);  
    12.         }  
    13.   
    14.         public function handleRequest()   
    15.         {  
    16.             $op = isset($_GET['op']) ? $_GET['op'] : NULL;  
    17.             switch ($op)   
    18.             {  
    19.                 case 'logout' :  
    20.                     $this->signout();  
    21.                     break;  
    22.                           
    23.                 case 'login':  
    24.                     $this->login();  
    25.                     break;  
    26.                   
    27.                 case 'signup' :  
    28.                     //To get user Details through it's id  
    29.                     $this -> signUp();  
    30.                     break;  
    31.                                   
    32.                 case NULL :  
    33.                     if (isset($_SESSION['userid']))   
    34.                     {  
    35.                         $user = $this -> userobj -> selectUserById($_SESSION['userid']);  
    36.                         include 'View/user_profile.php';  
    37.                     }  
    38.                     else  
    39.                     {  
    40.                         include 'View/homepage.php' ;  
    41.                     }  
    42.                     break;  
    43.                   
    44.                 default:  
    45.                     // other operation  
    46.             }  
    47.         }  
    48.           
    49.           
    50.         public function signout()   
    51.         {  
    52.             session_destroy();  
    53.             $this->redirect("index.php");  
    54.         }  
    55.           
    56.         public function redirect($location)  
    57.         {  
    58.             header('Location:'.$location);  
    59.         }  
    60.           
    61.         public function login()  
    62.         {  
    63.             if (isset($_SESSION['userid']))   
    64.             {  
    65.                 $user = $this -> userobj -> selectUserById($_SESSION['userid']);  
    66.                 include 'View/user_profile.php';  
    67.             }  
    68.             elseif (isset($_POST['loginbtn']))   
    69.             {  
    70.                 $name = $_POST['name'];  
    71.                 $password  = $_POST['password'];  
    72.                 $user = $this->userobj->login($name$password);  
    73.                 if ($user)   
    74.                 {  
    75.                     $_SESSION['userid'] =  $user->id;  
    76.                     include 'View/user_profile.php';  
    77.                 }  
    78.             }  
    79.             else   
    80.             {  
    81.                 echo "Wrong Admin name/Password";  
    82.             }  
    83.         }  
    84.           
    85.         public function signUp()  
    86.         {  
    87.             if (isset($_SESSION['userid']))   
    88.             {  
    89.                 $user = $this -> userobj -> selectUserById($_SESSION['userid']);  
    90.                 include 'View/user_profile.php';  
    91.             }   
    92.             elseif (isset($_POST['signupbtn']))   
    93.             {  
    94.                 $name = $_POST['name'];  
    95.                 $password = $_POST['password'];  
    96.                 $address = $_POST['address'];  
    97.                 $user = $this -> userobj ->signup($name,$password,$address);  
    98.                 $_SESSION['userid'] = $user;  
    99.                 $user = $this -> userobj -> selectUserById($_SESSION['userid']);  
    100.                 include 'View/user_profile.php';  
    101.             }   
    102.             else   
    103.             {  
    104.                 echo "blank";  
    105.             }  
    106.         }  
    107.           
    108.     }  
    109. ?>  
  • The user controller session is begun in the first line of the file.

    View/Homepage.php code snippet
    1. <!Doctype html>  
    2. <html>  
    3.     <head>  
    4.         <title>Homepage</title>  
    5.     </head>  
    6.     <body>  
    7.         <h1>Sign Up</h1>  
    8.         <form method="post" action="index.php?op=signup">  
    9.             <input type="text" id="name" name="name" placeholder="name" required/>  
    10.             <input type="password" id="password" name="password" placeholder="password" required/>  
    11.             <input type="text" id="address" name="address" placeholder="address" required />  
    12.             <input type="submit" id="submitbtn" name="signupbtn" value="Signup"/>  
    13.         </form>  
    14.         <h1>Login</h1>  
    15.         <form method="post" action="index.php?op=login">  
    16.             <input type="text" id="name" name="name" placeholder="name" required/>  
    17.             <input type="password" id="password" name="password" placeholder="password" required/>  
    18.             <input type="submit" id="submitbtn" name="loginbtn" value="Login"/>  
    19.         </form>  
    20.     </body>  
    21. </html>  

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. 


Similar Articles