PHP MVC: Model, View, Controller

  • In PHP, MVC is the collation of three core parts: Model, View, and Controller.
  • The visual representation of MVC is:
PHP MVC
  • The controller is the mediator between the model and view.
  • MVC framework hides the complex implementation details of applications.
  • It also increases the productivity of developers by basic implementations such as database connection, etc. are already partially implemented.

Model

  • In the overall design of the application, the permanent storage of data is the model.
  • In the overall pattern, it is the bridge between the view component and the controller component.
  • One important thing in the model is that it does not know what happens to the data when it is passed to the view or controller components.
  • Its main purpose is to process data into its permanent storage and prepare data to be passed along to the other parts.
  • The Model act as a gatekeeper to the data itself, which accepts all the request which comes in its way.
  • In an application, the model can be referring to JSON, XML, and even the database table structures.

View

  • View handles the presentation of data to the user.
  • Web application that are build using MVC, the View is the part of the system where the HTML is generated and displayed. 
  • The View, catch the reactions from the user, which then interact with the controller.
  • Views can be HTML, CSS, tables, lists, diagrams, etc.

Controller

  • The final component is the controller whose job is to handle data that the user inputs and update the model accordingly.
  • The user interact with the controller, without which the controller has no use.
  • We can say controller as a collector of information. This information is then passed to the Model for storage.
  • The controller is the server-side script – PHP, ASP, JSP, Python, etc…
  • One of the example of MVC in PHP is, processing a user registration form and recording a new entry into the database (view – controller – model).

Example

Lets create web application in PHP which is based on MVC.

Model:-

<?php
	class Model{
		public $text;
		public function __construct(){
			$this->text = "Hello World!";
		}
	}
?>

View:

<?php
	class View{
		private $model;
		private $controller;
		public function __construct($controller, $model){
			$this->controller = $controller;
			$this->model = $model;
		}
		public function output(){
			return "<p>" . $this->model->text . "</p>";
		}
	}
?>

Controller

<?php
	class Controller{
		private $model;
		public function __construct($model){
			$this->model = $model;
		}
	}
?>

Now we set up the relationships between them:

<?php
	$model = new Model();
	$controller = new Controller($model);
	$view = new View($controller, $model);
	echo $view->output();
?>