Model View Controller(MVC) in PHP
Patterns August 10th, 2009The model view controller pattern is the most used pattern for today’s world web applications. It has been used for the first time in Smalltalk and then adopted and popularized by Java. At present there are more than a dozen PHP web frameworks based on MVC pattern.
Despite 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.
July 4th, 2010 at 6:09 am
A nicely written tutorial. I now understand the MVC model. However, one thing is not clear: in your reply to Lau.
“The book class will be used in the view layer so it should be a simple data object”.
So what is implied by “book class used in the view layer”. How and why is model class used in View. Also stated in your article
“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”.
This is not clear as how and why Entity class is exposed to View Layer
Admin: The entity should be exposed because the data require a structure. The view and the model need to speak a “common language”. That is represented by the entity classes.
July 5th, 2010 at 1:25 am
Hi,
thanks a for a step by step tutorial with examples broken into great depth.
I tried going through some of the MVC tutorials,they just went above my head without any learning.thanks a lot again.
–
rgds
August 11th, 2010 at 11:26 pm
First Thanks for a very informative Tutorial. I’m almost there
.
You mentioned above :
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.
Does this mean that each function that is being required from the Controller has to be implemented in one Model. E.g:
include_once(“model/Book.php”);
include_once(“model/Teacher.php”);
include_once(“model/Students.php”);
class Model {
public function getBookList(){}
public function getBook($title){}
public function getTeacher($name){}
public function getStudent($name){}
}
Thanks in advance for the Answer.
Admin: Yes, that’s true.
September 9th, 2010 at 7:34 pm
Probably the best article/tutorial on MVC. Simple, concise and the example works on first run. Thanks!
September 17th, 2010 at 8:04 am
simple, yet very informative, well done!
September 27th, 2010 at 1:17 am
This is very good tutorials for beginner….
October 13th, 2010 at 4:45 am
Nice tutorial. Is there anyone know how to implement MySQL database and CRUD in this Model class? I tried to experiment it in this model class but it looks like unfortunate. Do PHP activerecord and PERL handle this? Some reviews said both probably handle them within your concept than own one.
October 23rd, 2010 at 10:26 pm
Wow. Great Tutorial! Very clear and helpful.
Thanks.
October 26th, 2010 at 6:13 am
MVC pattern was displayed very easy format. Using this tutorial , new guys easy OOPs PHP very quickly.
October 26th, 2010 at 6:19 am
1. Plz , tell me how to genarate getBookList() in model/Model.php using database?
2. Plz , tell me how to genarate getBook($title) in model/Model.php using database?
3. Then i want add one book , how can i create form?
4. I want Add/Edit/delete functionalities for the book. So plz reply soon.
If you reply very earlier , it will be very useful for me.
November 5th, 2010 at 11:24 am
Dude, thanks for this small article. This is exactly what I was looking for: a simple tutorial with PHP code and not framework-specific. Thanks for taking the time to share.
Regards,
MV
November 11th, 2010 at 7:22 am
I have always been confused with how MVC works with php and even more confused when looking at others tutorials on the web (There’s quite a lot out there) but it’s the first time I’m getting a clear understanding about MVC with this tutorial. The best I came across on the web. Thanks a lot for sharing this. May God bless you.
November 18th, 2010 at 9:45 am
Guys, before asking how to do more with this example, please keep in mind that it is just an example simplified at maximum to ease the understanding of MVC pattern. This is the one and only purpose. So, I would recommend not to rely on it for real projects especially if you don’t know how to query the db in php or how to create forms.
November 22nd, 2010 at 12:53 am
Thank you very much to the author for writing such a useful article. Now I get more familiar with the MVC. However, I still got a question, hoping someone can explain.
Refering to Furqan’s example of including the book, teacher, student into the Model, won’t it be too clumsy for such a big Model class? Say, now I just need to get a book into the book model, it’s useless to include teacher and students (and potentially more classes in the future). Why not split it into smaller ones that’s specific to the related classes? As later on, I may write other book retrieval methods like by author, ISBN etc. It’ll be hard to maintain such a big Model with all unrelated methods scrambled together.
I would expect a book specific model class, that queries the DB, and return the required books I want. Then have it put in the Book class and returned to the corresponding View. This way, we can have a manageable Model class while still able to pass the simple data object around.
I’m not sure my idea is correct, but let’s share and discuss
November 22nd, 2010 at 2:40 am
Awesome!!! The best example I found! Easy to understand and follow. Thanks!
November 23rd, 2010 at 10:23 am
Thank you for this clear, concise, simple overview. It is exactly what I was looking for. I’ve been coding PHP for about 13 yrs. I use Objects and Classes and DALs but I’ve never really grokked MVC, no matter how many other articles I’ve read. This hit it home with the exact level of abstraction I needed to start writing with MVC in mind (as opposed to just blindly bashing at code and using a hammer to make it fit into the file structure.)
November 23rd, 2010 at 7:36 pm
Very good tutorial, thanks.
November 24th, 2010 at 2:31 pm
Although i still don’t beging with mvc, i’m searching the web for good tutorials to start and i believe than this is a very good tutorial.
Sorry, my english is bad.
From Colombia.
December 8th, 2010 at 7:54 am
Thanks for such a helpful article. Having used some object oriented code written by others, and hacking stuff together in the Palm development environment, I can get things to run, but until now have really had trouble seeing the logic behind the structure, and having this example was clutch. Thanks a million!
January 6th, 2011 at 8:21 am
Hi I liked your article a lot . But I have a ques..
bookList.php and viewBook.php are the files in the view folder and they come under the presentation part
which is supposed to be just the html code. Is there a way I can remove this php code from the html file. I dont want to put php code in my html files. So if you have any solution to this . Please do reply me.
Thanks
January 12th, 2011 at 9:46 am
Nice tutorial. Would be better if filenames preceded every code snippet. You’ve done this on a few of them but some have been missed.
January 16th, 2011 at 3:49 pm
How can i create the Database and request in MVC? I have tried it but it’s difficult than non-MVC. Has anyone experienced it and simplified the example?
January 26th, 2011 at 11:24 am
Hi, I’m new to this MVC style coding and kind of just thrown in the deep end on programming in this framework and was wondering about a few things…
So in the “Model.php” page on line 8 where the array of books start, how would you use a database connection in here?
**************************************************************
mysql_connect(“localhost”,”username”,”password”);
mysql_select_db(“dbname”);
and after a connection, where would you place something like this:
$sql = mysql_query(“select tableName1, tableName2, tableName3 from table”);
while ($row = mysql_fetch_array($sql)) {
$title = “$row[1]“;
}
Thx,
RT
January 27th, 2011 at 4:46 pm
Thanks a lot …for ‘very informative tutorial’
January 29th, 2011 at 2:27 am
Great tutorial! Thank you very much. Although I do not speak english very well I understand whole tutorial. thank you.
January 30th, 2011 at 6:37 am
Great overview, I really like the diagrams.
I am playing catchup in going from procedural programming to OO and Web development, so this really helps.
February 19th, 2011 at 4:22 am
That would be ok for a start…
February 21st, 2011 at 1:09 am
Hello,
I’m kinda new to MVC and this tutorial was so helpful for me. I was just wondering is there any way to make these urls more SEO friendly. ( using the .htaccess file )
Eg : http://localhost/mvc/index.php?book=PHP for Dummies to http://localhost/mvc/book/PHP for Dummies
Any advice given would be greatly appreciated.
Cheers
Mahesh
March 25th, 2011 at 2:54 pm
One of the cleanest implementations of MVC I have ever seen.
Would be nice to follow this post up with a few ammendments and additions, i.e. a Registry class for storing all your PHP constants etc… and some really basic database setup stuff.
Really useful post.
April 1st, 2011 at 3:18 pm
For over 10 years, I have used an object for my database calls, happy that if I switched to postGres, etc., I would only have to use a new global.inc file and change my queries.
I also have refined a custom funcs.inc file with my teams that is useful across various applications with a few mods for each. The php web pages serve as the view/model for me just fine, and any common calls are made into functions or more includes to build arrays to show in the view.
I have yet to run into a downside with this approach, except in how it may be less conducive to team programming. The logic is very clean and less code loads up in each apache request.
What am I missing?
April 5th, 2011 at 11:11 pm
HELLO
Nice tutorial ONE OF THE BEST ON THE WEB … and it works
bye !
April 12th, 2011 at 11:39 pm
Thank u for posting.
April 18th, 2011 at 4:21 pm
Excellent tutorial!!!
I would love to see more about MVC.
April 30th, 2011 at 4:37 pm
Great tutorial!
I’m kindda new to mvc and oo, I really enjoy learning new stuff.
I would like to make a login(DB) page and add,edit new records (CRUD) based on this tutorial, does any one wants to give me a hand? I’m working on CRUD right now,
so if you’re interested in continuing this tutorial, please post here or email me at meegloz at myopera dot com.
Maybe we can post the final work here,
Thanks!
May 11th, 2011 at 11:34 am
This is a great tutorial. I have to disagree with “admin” that you should not jump into MVC using what you learned in this tutorial. Granted yes, you still need more, like an understanding of database interaction, but I think it is a much better stepping stone to try to make some basic projects with a self-created basic MVC framework rather than overwhelming yourself with a more professional framework that may even be overkill for what you need.
May 16th, 2011 at 5:11 pm
Thank you so much for the excellent tutorial.
I’ve been designing a site while using your tutorial as a reference, and I’ve hit a gray area with respect to the relationships among the components when lets say the view contains an html form that uses POST. Should the action attribute be set to the controller or index.php?
Also, assuming you POST directly to the controller, if there’s a cycle where the controller includes the view and the view POSTS to the controller, how can one keep the relative paths in order.
May 19th, 2011 at 4:27 am
This is a really cool example of how MVC works, thank you thank you thank you
May 19th, 2011 at 6:33 am
its really nice..easily can understand..thanks
June 1st, 2011 at 7:10 pm
Excellent tutorial.I have already learned html.But I didn’t clear idea.Your blog tutorial is so easy to practice and learn.Thanks for adding this in your blog.
June 9th, 2011 at 7:47 pm
Thanks a lot mate
Could you please write more articles about the MVC pattern please.
Thanks again
June 21st, 2011 at 3:41 am
VERY NICE TUTORIAL
June 22nd, 2011 at 1:21 am
Hello,
Thank you very much for such a lovely example but m able to run it..
I kept the mvc folder in my htdocs & called index.php but it directly
shows the content of index.php rather than showing books list.
Any help will be appreciated.
June 25th, 2011 at 12:08 am
Nice tutorial ONE OF THE BEST
June 26th, 2011 at 6:37 pm
This guide is what I’m looking for. So far I got it from framework and need more for my student, I learn much from this. Thank you very much.
June 27th, 2011 at 4:10 am
this is great ………..
thanks so much……
July 1st, 2011 at 5:33 am
Wow awesome tutorial

MVC is now a lot more clearer to me
Thanks!!
July 8th, 2011 at 1:31 pm
Hi!. this post is very interesting, but… how I can insert records in a Data Base?
Thanks
September 5th, 2011 at 5:34 am
Nice Tutorial for MVC
September 8th, 2011 at 9:42 am
In the book class, the attributes have public access. It is good practice to make these attributes private and have public accessors, e.g. public getTitle(), getAuthor() and getDescription(). However, once this is done, the views, e.g. booklist.php would need to use these methods. I have read in other MVC posts and tutorials that only “simple php” should be used in views. Is the passing of objects to views and the use of more complex php access methods acceptable?
September 18th, 2011 at 8:25 pm
Thank you very much,this is a nice tutorial.The code in view module needs a little explanation i.e how you call the $title in view.
October 5th, 2011 at 10:23 am
Interesting very clear, but what about setting and getting how can I implement it? in other tutorial they say set and get is very important Im confused
October 27th, 2011 at 7:32 am
it’s so simple but clear most to illustrate the php mvc, thanks
October 27th, 2011 at 3:08 pm
@Gammerz
1. First of all this is just an introduction to MVC framework in PHP. Some things might not be the same in “real life”.
2. I don’t find any reason for which not to use getters/setters in views. This refers to the principle of encapsulation and should be generally valid regardless the layer where you are. Further more if the same object is used in 2 layers encapsulation should be used to a achieve a better degree of decoupling.
October 31st, 2011 at 10:02 pm
thankssssss it’s a gr8 tutorial
November 4th, 2011 at 10:04 am
Excelent tutorial, easy to understand and with actually working code.
This is the best simply-tiny MVC project on the web, the second is KissMVC. It would be great, if someone create next episode of this, with real basic examples of use (or sharing his little project).
I need create similar framework for my bachelor work, or use this.
(sorry for my English, i’m from Czech Republic – Central Europe).
December 23rd, 2011 at 3:12 am
Its a great tutorial for mvc..
January 7th, 2012 at 11:00 am
Thanks, this is best simple MVC tutorial which is i am looking for.
Excellent job
Thanks for sharing.
January 12th, 2012 at 1:32 pm
Great tutorial, easy to understand, just what I was looking for. Sometimes is hard to find this kind of explanations which you need if you’re kind of noob (like me)
January 16th, 2012 at 12:59 am
Thank you very much! Out of all the MVC with PHP explaination out there, I think this tutorial is the easy to understand.
I really don’t like those emphasize too much on .htaccess, folders organization & superclass together into the tutorial. It just complicate things. Should leave the in depth detail of SEO, OO, layered architecture, theory of design pattern etc out.