In this article am going to explain about the basics of MVC in PHP includes what it is,the basic structure and implementation of MVC in PHP. Hope it helps for beginners.

What is MVC ?

  • Model-View-Controller (MVC) is an architectural pattern used in software engineering.
  • Model represents the information on the application.
  • View resembles to elements of the user interface such as text,button and so on.
  • Controller executes the intercommunication of data and business rules used to manage the data to and from the model

A pictorial representation of MVC pattern.

mvc-pattern

Let’s start with a basic example using MVC in PHP

  • First we have to create a folder named application inside the www folder in Wamp server.if you are using Wamp server.
  • Inside the application folder create model,view and controller folders and PHP file named index.

mvc-img

Controller

Create a Controller.php file inside the folder controller and copy the following code into it.

[sh lang=”php”]

<?php

include_once(“model/Model.php”);

class Controller {

public $model;

public function __construct()

{

$this->model = new Model();
}

public function invoke()

{

$reslt = $this->model->getlogin();     // it call the getlogin() function of model class and store the return value of this function into the reslt variable.

if($reslt == ‘Welcome to seamedia’)

{

include ‘view/Welcome.php’;

}

else

{

include ‘view/login.php’;

}

}

}

?>[/sh]

Model

Create a Model.php file inside the folder model and copy the following code into it.

[sh lang=”php”]

<?php

include_once(“model/Model.php”);

class Model

{

public function getlogin()

{

if(isset($_REQUEST[‘user’]))

{

if($_REQUEST[‘user’]==’seamedia’)

{

return ‘Welcome to seamedia’;

}

else

{

return ‘Not applicable’;

}

}

}

}

?[/sh]

View

Create two PHP files login.php and Welcome.php file inside the folder view and copy the following code into it.

login.php

[sh lang=”php”]

<html>

<head></head>

<body>

<?php

echo $reslt;

?>

<form action=”” method=”POST”>

<p>

<label>User</label>

<input id=”user” value=”” name=”user” type=”text” required=”required”/><br>

</p>

<p>

<button type=”submit” name=”submit”><span>Login</span></button>

<button type=”reset”><span>Cancel</span></button>

</p>

</form>

</body>

</html[/sh]

Welcome.php

[sh lang=”php”]
<html>
<head></head>

<body>

<?php

echo $reslt;

?

</body>
</html>[/sh]

index.php

Open index.php and copy the following code.
[sh lang=”php”]
<?php

include_once(“controller/Controller.php”);

$controller=new Controller();

$controller->invoke();

?[/sh]

Output

mv-login