Model View Controller in PHP
Patterns August 10th, 2009Despite the fact that the MVC pattern is very popular in PHP, is hard to find a proper tutorial accompanied by a simple source code example. That is the purpose of this tutorial.
-
The MVC pattern separates an application in 3 modules: Model, View and Controller:
- The model is responsible to manage the data; it stores and retrieves entities used by an application, usually from a database, and contains the logic implemented by the application.
- The view (presentation) is responsible to display the data provided by the model in a specific format. It has a similar usage with the template modules present in some popular web applications, like wordpress, joomla, …
- The controller handles the model and view layers to work together. The controller receives a request from the client, invoke the model to perform the requested operations and send the data to the View. The view format the data to be presented to the user, in a web application as an html output.
The above figure contains the MVC Collaboration Diagram, where the links and dependencies between figures can be observed:

Our short php example has a simple structure, putting each MVC module in one folder:

Controller
The controller is the first thing which takes a request, parse it, initialize and invoke the model and takes the model response and send it to the presentation layer. It’s practically the liant between the Model and the View, a small framework where Model and View are plugged in. In our naive php implementation the controller is implemented by only one class, named unexpectedly controller. The application entry point will be index.php. The index php file will delegate all the requests to the controller:
// index.php file
include_once("controller/Controller.php");
$controller = new Controller();
$controller->invoke();
Our Controller class has only one function and the constructor. The constructor instantiate a model class and when a request is done, the controller decide which data is required from the model. Then it calls the model class to retrieve the data. After that it calls the corresponding passing the data coming from the model. The code is extremely simple. Note that the controller does not know anything about the database or about how the page is generated.
include_once("model/Model.php");
class Controller {
public $model;
public function __construct()
{
$this->model = new Model();
}
public function invoke()
{
if (!isset($_GET['book']))
{
// no special book is requested, we'll show a list of all available books
$books = $this->model->getBookList();
include 'view/booklist.php';
}
else
{
// show the requested book
$book = $this->model->getBook($_GET['book']);
include 'view/viewbook.php';
}
}
}
In the following MVC Sequence Diagram it can be observed the flow during a http request:

Model and Entity Classes
-
The Model represents the data and the logic of an application, what many calls business logic. Usually, it’s responsible for:
- storing, deleting, updating the application data. Generally it includes the database operations, but implementing the same operations invoking external web services or APIs is not an unusual at all.
- encapsulating the application logic. This is the layer that should implement all the logic of the application. The most common mistakes are to implement application logic operations inside the controller or the view(presentation) layer.
In our example the model is represented by 2 classes: the “Model” class and a “Book” class. The model doesn’t need any other presentation. The “Book” class is an entity class. This class should be exposed to the View layer and represents the format exported by the Model view. In a good implementation of the MVC pattern only entity classes should be exposed by the model and they should not encapsulate any business logic. Their solely purpose is to keep data. Depending on implementation Entity objects can be replaced by xml or json chunk of data. In the above snippet you can notice how Model is returning a specific book, or a list of all available books:
include_once("model/Book.php");
class Model {
public function getBookList()
{
// here goes some hardcoded values to simulate the database
return array(
"Jungle Book" => new Book("Jungle Book", "R. Kipling", "A classic book."),
"Moonwalker" => new Book("Moonwalker", "J. Walker", ""),
"PHP for Dummies" => new Book("PHP for Dummies", "Some Smart Guy", "")
);
}
public function getBook($title)
{
// we use the previous function to get all the books and then we return the requested one.
// in a real life scenario this will be done through a db select command
$allBooks = $this->getBookList();
return $allBooks[$title];
}
}
In our example the model layer includes the Book class. In a real scenario, the model will include all the entities and the classes to persist data into the database, and the classes encapsulating the business logic.
class Book {
public $title;
public $author;
public $description;
public function __construct($title, $author, $description)
{
$this->title = $title;
$this->author = $author;
$this->description = $description;
}
}
View (Presentation)
The view(presentation layer)is responsible for formating the data received from the model in a form accessible to the user. The data can come in different formats from the model: simple objects( sometimes called Value Objects), xml structures, json, …
The view should not be confused to the template mechanism sometimes they work in the same manner and address similar issues. Both will reduce the dependency of the presentation layer of from rest of the system and separates the presentation elements(html) from the code. The controller delegate the data from the model to a specific view element, usually associated to the main entity in the model. For example the operation “display account” will be associated to a “display account” view. The view layer can use a template system to render the html pages. The template mechanism can reuse specific parts of the page: header, menus, footer, lists and tables, …. Speaking in the context of the MVC pattern
In our example the view contains only 2 files one for displaying one book and the other one for displaying a list of books.
viewbook.php
<html> <head></head> <body> <?php echo 'Title:' . $book->title . '<br/>'; echo 'Author:' . $book->author . '<br/>'; echo 'Description:' . $book->description . '<br/>'; ?> </body> </html>
booklist.php
<html>
<head></head>
<body>
<table>
<tbody><tr><td>Title</td><td>Author</td><td>Description</td></tr></tbody>
<?php
foreach ($books as $title => $book)
{
echo '<tr><td><a href="index.php?book='.$book->title.'">'.$book->title.'</a></td><td>'.$book->author.'</td><td>'.$book->description.'</td></tr>';
}
?>
</table>
</body>
</html>
The above example is a simplified implementation in PHP. Most of the PHP web frameworks based on MVC have similar implementations, in a much better shape. However, the possibility of MVC pattern are endless. For example different layers can be implemented in different languages or distributed on different machines. AJAX applications can implements the View layer directly in Javascript in the browser, invoking JSON services. The controller can be partially implemented on client, partially on server…
-
This post should not be ended before enumerating the advantages of Model View Controller pattern:
- the Model and View are separated, making the application more flexible.
- the Model and view can be changed separately, or replaced. For example a web application can be transformed in a smart client application just by writing a new View module, or an application can use web services in the backend instead of a database, just replacing the model module.
- each module can be tested and debugged separately.
The files are available for download as a zip from http://sourceforge.net/projects/mvc-php/files/mvc.zip/download




August 12th, 2009 at 2:36 pm
I might be being a little picky here. I admit, I’m not a PHP guy I’m a Java, C# guy. But the Model is the data, not necessarily the mechanism for retrieving the data. In the Java world we have Business Logic and Persistence layers that handle those functions. And the Model is just a representation of data used by a view.
Of course this might be different in the PHP world.
August 12th, 2009 at 2:48 pm
This is a big and exhaustive discussion but I dream that one day people will stop calling PHP developers script kiddies so here’s my attempt:
Model should take care of business logic, NOT only datam while the Controller should take care of the app logic.
In your example, the model should have a function getBookByTitle() which is used by the Controller.
I’ll write about MVC in PHP when I have the time to do it. Any way thank you for your attempt. It certainly help people. Still, be careful with what you write.
The great majority of the articles about MVC I read on the internet have wrong informations in them.
Read more at http://www.littlehart.net/atthekeyboard/2007/04/27/fat-models-skinny-controllers/
August 13th, 2009 at 6:48 am
Nice little primer here, thanks for this, i’ve been looking for something like this that skims the surface - i’m finding that most of the tutorials on the web are too technical. You’ve broken it down quite nicely.
Thanks again!
August 15th, 2009 at 2:03 pm
@Tom Qualile, I agree in Java and other languages there are specialized layers for Persistence. This example is a simple one just to explain the MVC pattern. After all in a MVC architecture the Persitance layer is just a part of the Model.
@Bruno Cassol: the model already includes “public function getBook($title)”
August 19th, 2009 at 5:25 am
What is the difference between business logic and app logic? Im really new to php architecture and am learning the ropes of php. Im Trying to learn more about PHP, OOP in general. I want to do web application development.
MVC patterns are a little fuzzy to me though.
November 1st, 2009 at 1:51 am
Maby it’s handy to add the source attatched to your site, so ppl can try your example without copying and pasting the content.
November 4th, 2009 at 7:46 am
Bussines logic is usualy located in in the model layer. In most of the cases it defines the operations that can be done in the “backstage”: Examples of business rules:
- A library can store only 1000 books.
- Each book should have at least one author.
- Each time a book is returned the application should send a mail to the librarian.
The app logic is located usually in the controller area. It is more related with the operations visible to the user. For example the application logic defines which objects in the model layer should be used for a specific request and what layout should be displayed. Application logic can also define the order in which the screens are displayed.
In practice the border between application logic and business logic is not always very visible.
November 4th, 2009 at 11:23 am
Thans @Bruggema, the files are available for download at http://sourceforge.net/projects/mvc-php/files/mvc.zip/download
January 13th, 2010 at 10:43 am
This was exactly what I was looking for. A simple explanation on the MVC model with a simple example to go with it.
Thanks a bunch!
March 8th, 2010 at 2:43 pm
Well this is the first time I completed an MVC tutorial and understand it. Thanks.
April 12th, 2010 at 10:01 am
Great tutorial! Finally a tutorial, with actual working code! A great started to start with MVC in PHP.
April 17th, 2010 at 1:07 pm
Thanks for the high level overview, it’s what I was looking for.
May 13th, 2010 at 6:34 am
excelent tutorial, thanks.
May 26th, 2010 at 6:27 am
I have learned a lot on this example. Thank you for posting this tutorial.
June 2nd, 2010 at 3:13 am
This is a good tut. I am new to this. I have been searching for something like this but they are all too complicated. I could more or less grasp yours.
I am asking you in regard to Model.php file. How do you actually populate it with records existing from a database? And that it could be retrieved through the $title.
If you could find the time, I really would appreciate this extra learning.
Thanks a million!
June 3rd, 2010 at 10:20 am
this is the best MVC tutorial I came across so far. thanks for sharing!
I am new to MVC and I am still confused with the class Model and the class book in your example…
for instance, I have my website and the content of my webiste is pulled from a database… so when I request a specific page for instance, http://www.mysite.com/index.php?pg=profile or with clean url http://www.mysite.com/profile
so usually, I will get the content from the SQL query,
$sql = ”
SELECT * FROM root_pages
WHERE root_pages.pg_url = ‘”.$_REQUEST['pg'].”‘
“;
so then should this $sql be put in the class book or class model??
I have a directory folder which keeps all my CMS files, which contains update, insert, delete SQL queries, html forms, and pages that display the db items into lists, etc.
so if I implement MVC on my website, then I am going to relocate these CMS files into different locations, like some in the model folder, and some in view folder and others in controller folders, is it correct??
June 8th, 2010 at 3:13 pm
@Lau
1. From the MVC perspective it doesn’t really matter where the SQL code should be put. In this example there is a model class to demonstrate the MVC pattern. The main purpose of the model class is to provide a central point for all the operations exposed by the model. The book class will be used in the view layer so it should be a simple data object. A good practice would be to create a separate class that will handle the book db operations(a DAO layer inside the Model).
2. A pattern does not force you to use a standard folder structure. I personally think that it is better to split the files in separate folders. The 3 layers (M-V-C) should be as decoupled as possible. When you write your code try to imagine that you have to use the Model or the Presentation layer in another application. If you could achieve it by simply coping its directory then you have a good class design. If you have to change lots of files it means the classes are coupled(bad design).
June 18th, 2010 at 2:26 am
Just what I was looking for, a simple tutorial that clearly explains how MVC works with PHP at it’s simplest level.