Tutorial Details
- Difficulty: Beginner
- Architecture: MVC
Model-View-Controller (MVC) is probably one of the most quoted patterns in the web programming world in recent years. Anyone currently working in anything related to web application development will have heard or read the acronym hundreds of times. Today, we’ll clarify what MVC means, and why it has become so popular.
Ancient History…
MVC is not a design pattern, it is an Architectural pattern that describes a way to structure our application and the responsibilities and interactions for each part in that structure.
It was first described in 1979 and, obviously, the context was a little bit different. The concept of web application did not exist. Tim Berners Lee sowed the seeds of World Wide Web in the early nineties and changed the world forever. The pattern we use today for web development is an adaptation of the original pattern.
The wild popularization of this structure for web applications is due to its inclusion in two development frameworks that have become immensely popular: Struts and Ruby on Rails. These two environments marked the way for the hundreds of frameworks created later.

MVC for Web Applications
The idea behind the Model-View-Controller architectural pattern is simple: we must have the following responsibilities clearly separated in our application:

The application is divided into these three main components, each one in charge of different tasks. Let’s see a detailed explanation and an example.
Controller
The Controller manages the user requests (received as HTTP GET or POST requests when the user clicks on GUI elements to perform actions). Its main function is to call and coordinate the necessary resources/objects needed to perform the user action. Usually the controller will call the appropriate model for the task and then selects the proper view.
Model
The Model is the data and the rules applying to that data, which represent concepts that the application manages. In any software system, everything is modeled as data that we handle in a certain way. What is a user, a message or a book for an application? Only data that must be handled according to specific rules (date can not be in the future, e-mail must have a specific format, name cannot be more than x characters long, etc).

The model gives the controller a data representation of whatever the user requested (a message, a list of books, a photo album, etc). This data model will be the same no matter how we may want to present it to the user, that’s why we can choose any available view to render it.
The model contains the most important part of our application logic, the logic that applies to the problem we are dealing with (a forum, a shop, a bank, etc). The controller contains a more internal-organizational logic for the application itself (more like housekeeping).
View
The View provides different ways to present the data received from the model. They may be templates where that data is filled. There may be several different views and the controller has to decide which one to use.
A web application is usually composed of a set of controllers, models and views. The controller may be structured as a main controller that receives all requests and calls specific controllers that handles actions for each case.
Let’s See an Example
Suppose we’re developing an online book store. The user can perform actions such as: view books, register, buy, add items to current order, create or delete books (if he is an administrator, etc.). Let’s see what happens when the user clicks on the fantasy category to view the titles we have available.
We will have a particular controller to handle all books-related actions (view, edit, create, etc). Let’s call it books_controller.php for this example. We will also have a model, for example book_model.php, handling data and logic related to the items in the shop. Finally we will have a series of views to present, for example, a list of books, a page to edit books, etc.
The following figure shows how the user request to view the fantasy books list is handled:

The controller (books_controller.php) receives the user request [1] as an HTTP GET or POST request (we can also have a central controller, for example index.php receiving it and then calling books_controller.php).
The controller examines the request and the parameters and calls the model (book_model.php) asking him to return the list of available fantasy books [2].
The model is responsible for getting that information from the database (or wherever it is stored) [3], apply filters or logic if necessary, and return the data representing the list of books [4].
The controller will use the appropriate view [5] to present these data to the user [6-7]. If the request came from a mobile phone, a view for mobile phones will be used, if the user has a particular skin selected, the corresponding view will be chosen, and so on.
What are the Advantages?
The most obvious advantage we gain using MVC is a clear separation of presentation (the interface with the user) and application logic.
Support for different types of users using different types of devices is a common problem these days. The interface presented must be different if the request came from a desktop computer or from a cell phone. The model returns exactly the same data, the only difference is that the controller will choose a different view to render them (we can think of a different template).
Apart from isolating the view from the business logic, the M-V-C separation reduces the complexity when designing large applications. The code is much more structured and therefore easier maintain, test and reuse.
Ok, but Why a Framework?
When you use a framework, the basic structure for MVC is already prepared and you just have to extend that structure, placing your files in the appropriate directory, to comply with the Model-View-Controller pattern. Also you get a lot of functionality already written and thoroughly tested.
Take cakePHP as an example MVC framework. Once you have it installed, you’ll see three main directories:
- app/
- cake/
- vendors/
The app folder is where you place your files. It is your place to develop your part of the application.
The cake folder is where cakePHP has its files and where they have developed their part (main framework functionality).
The vendors folder is for third-party PHP libraries if needed.
Your working place (app directory) has the following structure:
- app/
- config/
- controllers/
- locale/
- models/
- plugins/
- tests/
- tmp/
- vendors/
- views/
- webroot/
Now you have to put your controllers in the controllers directory, your models in the models directory and your views in… the views directory!
Once you get used to your framework, you’ll be able to know where to look for almost any piece of code you need to modify or create. This organization alone makes maintainability a lot easier.
Let’s Framework our Example
Since this tutorial is not intended to show you how to create an application using cakePHP, we’ll use it only to show example code for the model, view and controller components and comment on the benefits of using an MVC framework. The code is oversimplified and not suitable for real applications.
Remember we had a book store and a curious user who wants to see the complete list of books in the fantasy category. We said that the controller will be the one receiving the request and coordinating the necessary actions.
So, when the user clicks, the browser will be requesting this url:
www.ourstore.com/books/list/fantasy
CakePHP likes to format URLs in the form /controller/action/param1/param2 , where action is the function to call within the controller. In the old classic url format it would be:
www.ourstore.com/books_controller.php?action=list&category=fantasy
Controller
With the help of cakePHP framework, our controller will look something like this:
<?php
class BooksController extends AppController {
function list($category) {
$this->set('books', $this->Book->findAllByCategory($category));
}
function add() { ... ... }
function delete() { ... ... }
... ... } ?>
Simple, isn’t it?. This controller will be saved as books_controller.php and placed in /app/controllers. It contains the list function, to perform the action in our example, but also other functions to perform other book-related actions (add a new book, delete a new book, etc).
The framework provides a lot of things for us and only one line is necessary to list the books. We have base classes with the basic controller behavior already defined, so we inherit from them (AppController which inherits from Controller).
All it has to do in the list action is call the model to get the data and then choose a view to present it to the user. Let’s explain how this is done.
this->Book is our Model, and this part:
$this->Book->findAllByCategory($category)
is telling the model to return the list of books in the selected category (we’ll see the model later).
The set method in the line:
$this->set('books', $this->Book->findAllByCategory($category));
Is the controller way to pass data to the view. It sets the books variable to the data returned by the model and makes it accessible to the view.
Now we just have to render the view, but this will be done automatically by cakePHP if we want the default view. If we need any other view we just have to call it explicitly using the render method.
Model
The model is even more simple:
<?php
class Book extends AppModel {
}
?>
Why empty? Because it inherits from a base class that provides necessary functionality and we have followed the CakePHP name conventions to allow the framework to do other tasks automatically. For example, cakePHP knows, based on names, that this model is used in BooksController and that it will access a database table called books.
With this declaration only we have a book model capable of reading, deleting or saving data from the database
The code will will be saved as book.php and placed in /app/models.
View
All we have to do now is creating a view (at least one) for the list action. The view will have the HTML code and a few (as few as possible) PHP lines to loop through the books array provided by the model.
<table> <tr> <th>Title</th> <th>Author</th> <th>Price</th> </tr> <?php foreach ($books as $book): ?> <tr> <td> <?php echo $book['Book']['title']; ?> </td> <td> <?php echo $book['Book']['author']; ?> </td> <td> <?php echo $book['Book']['price']; ?> </td> </tr> <?php endforeach; ?> </table>
As we can see, the view doesn’t produce a complete page, just an HTML fragment (a table in this case). This is because CakePHP provides another way to define the layout of the page, and the views are inserted into that layout. The framework also provides us with some helper objects to make common task easy when creating these HTML excerpts (insert forms, links, Ajax or JavaScript).
We make this the default view saving it as list.ctp ( list is the name of the action and ctp means cake template) and placing it in /app/views/books (inside books because these are views for books controller actions).
And this completes the three components with the help of CakePHP framework!
Conclusion
We have learned what is probably the most commonly used architectural pattern today. We must be aware though that when we talk about patterns in the programming world, we are talking about flexible frames, to be tailored to the particular problem at hand. We will find implementations introducing variations on the structure we have seen, but the important thing is that, in the end, the pattern helps us gain a clear division between responsibilities and better maintainability, code-reuse, and testing.
We have also seen the advantages of using an MVC framework that provides us with a basic MVC skeleton and a lot of functionality, improving our productivity and making the development process easier. Thanks for reading!

Woww .. Nice tut ..
Thnx Pablo
Sid
I’ve always found Djangos way of handlings things to be much more intuitive (but thats probably just me).
MVT (Model View Template) – It’s basically the same thing except the Views handle the user requests and the Templates handle the way the information is displayed to the user. Its basically the same thing except worded differently.
Hello,
If you are placing Rails next to PHP frameworks then I think you should also add ASP.NET MVC 1/2 logo.
I was learning about the whole MVC environment when starting with Ruby on Rails and I must admit it really confused me so much! I kinda got the simplified version but this tutorial has definitely opened up many new avenues.
Thanks for the tips, it has helped me that’s for sure!
It’s an important pattern to learn if you want to get into something like iPhone or desktop development. The iPhone, especially, is a very MVC and OOP-centric device.
Great article. First actually good one I’ve seen around. :)
Most helpful for newbies!
Great info! I’ve read a lot of breakdowns about MVC, and this is another that helped me clarify my thinking =)
Nice Tut.. I’ve been getting into CodeIgniter recently and still struggling with where some code should go between the controller and model. This has cleared it up a bit. Thanks
I must agree with first and second user. I had a problem of understanding it to, but it clarified and gave some knowledge about MVC, that I didn’t new.
Also I must say, that even so it is a great tutorial, still it would be better if author or any one else who is planing to make such tut, would be able to make a working example, which is not based on a framework (even if it would look ugly as hell).
Great tutorial for starters! :)
good explanations of mvc.
Thanks.
Where was this 6 months age when I tried to figure out what the heck a MVC was? I have the hang of it now and really like the concept. Also the fourth image was really helpful!
Very nice Tutorial.
Now I feel also like testing CakePHP :)
Since I was starting a small community page, I was first doing everything on my own (dynamic page loading and all that stuff), but I think I might try to make it using a Framework. Maybe it’ll actually make my code clearer and maybe even faster to develop.
Thanks for that!
I don’t like the title, I think its offensive and rude. it should be newbies or beginner, noob (In My Opinion), is a very harsh way of putting it, its like saying MVC for dumb-asses or idiots, which we are not, some of us are inexperienced and need help, putting it in terms of noobs I don’t think is very nice.
However, the content of the tutorial was very good, and it certainly helped me,
Thanks.
You’re kidding, right? Newbies/beginners/noobs all mean the same thing. Stop getting offended so easily.
Pardon me but… it’s YOU who’s kidding… right?
V~gina, p~ssy, c~nt all *mean* the same thing, too. What makes them different isn’t the meaning, but the cultural markers, connotations, and implications. Do you think those terms, while *meaning* the same thing, convey different attitudes among those who use one term rather than the others? Do you think those terms, when used in the presence of a woman, or particular in conversation *with* or *about* the woman, show different levels of respect?
(Note: if you answered “no” to either of those questions, don’t bother to read any more of this reply; you most likely receive the message even if you understand the words).
I’ve rarely seen “noob” used as a term of respect for one’s first steps in a particular direction. Usually it’s a reference to someone’s ineptness, and meant in a derogatory context with respect to their beginner-ness.
“Wise men talk because they have something to say; fools, because they have to say something.” (Plato).
If thats what he meant he would have made it “MVC for Idiots”
Or, MVC for “Dummies” ?
“MVC” an Idiots guide ?
come on ….
You do know that Noob orginates from the word Newbie. It actually is the same thing as Newbie. Although maybe not “exactly” the same as beginner. (Ofcourse they all mean the same thing, but they have different weights).
This is the Web mate, noob is just short for newbie.
Does the controller not handle the biz logic?
Example:
function login()
{
// validate form input from VIEW
// check user credentials against MODEL
// if success – set session and show success VIEW
// else
// show fail VIEW
}
Nope, the controller should not handle the biz logic. That’s the domain model’s job. To pick up on your example:
// validate form input from VIEW
// check user credentials against MODEL
Those are both model tasks and the procedure of both can CHANGE. Do you want to rewrite your controller when login validation rules have changed? All the controller needs to know is wether you have a valid user or not in order to redirect to the corrct action. The controller should not care WHY a user is valid, just if he is or not.
When you login you normally use just a login name and a password. You probably only check wether the form fields are empty or not. A controller could handle that. But what if you want to validate a phone number? You will use some kind of regex or check against the database. No task a controller should do. What if your company goes international and you will now have to validate phone numbers from 30 countries? Will you blow up your controller logic?
All a controller should do is to direct the flow of the application. Get the request, invoke the model and direct to the correct view. Keep it as lean as possible.
Another advantage of that is that your controllers are easily testable.
Another big reason why you should keep the complete business logic inside the model is, that you can reuse that model with other GUIs. What if your boss wants a desktop app of that stuff? Will you copy the controller logic? And where will you put it? Desktop apps don’t follow MVC. Nope – keep it in the model stay independent of the environment it is used in.
so it goes
function login(user)
{
// if valid(user)
// show success view
// else redirect to login view
}
Let valid(user) take care of the rest.
Actually, many desktop apps use MVC (http://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller#Implementations_of_MVC_as_GUI_frameworks) – have a look at the Swing framework in Java.
better to have component to handle user identity, data sort, data pagination. Either controller nor model is right place for that
nice artical its really good MVC for Rail is good, but I am hopeing soon we can see ASP.NET MVC also in details.
please if possible any Rail MVC tutorial please make 1 for ASP.NET MVC also same tutorial just in place of Rail ASP.net
There is an excellent free tutorial on ASP.NET MVC 1.0 from Scott Guthrie, the leading developer of the framework right here
I second that.. A MVC tutorial on ASP.NET will help clear a lots of my doubts.
Awesome overview of MVC concepts. I’ll send people here next time I’m trying to convince someone to stop writing giant PHP scripts that handle all layers of the application.
Thanks for this one! Exactly what I needed!
This is great stuff for noob like me to learn and understand what MVC is all about.
Thanks
I don’t agree with model is both data and business logic. A model in the context of mvc contains the data to view in the view, and nothing more. The business logic is in a different model, most of the times connected to a database. The same model can be presented in different ways to a user in different views. It’s much easier to program small models with separate tasks than trying to fit everything in one model. The controller part of the application is responsible for mapping the domain model in a viewmodel, to show the view. The model in mvc, is just a container of data passed around between the view and controller. Nothing more.
class Controller
method Get(modelWithDataFromUrl)
viewModel = findViewModel(modelWithDataFromUrl.Part1, modelWithDataFromUrl.Part2)
showTheView(viewModel)
method Post(modelWithDataFromUrlAndThePostedHtmlForm)
// do validation
domainObject = findDomainObject(modelWithDataFromUrlAndThePostedHtmlForm.Id)
domainObject.DoBusinessLogic(modelWithDataFromUrlAndThePostedHtmlForm.Thing1, modelWithDataFromUrlAndThePostedHtmlForm.Thing2)
viewModel = createViewModel()
showTheView(viewModel)
I disagree.
What you describe is a plain “viewmodel”, a concept you can find in ASP.NET MVC for example. There you build custom classes from your business model objects in order to meet the needs of the view concerned about presenting this data. The biggest advantage here is, that you get IntelliSense (Code Assist) support within the view. But you need a strongly typed language for that, so it’s useless in PHP frameworks.
You state “The business logic is in a different model, most of the times connected to a database.” That’s exactly what you should NOT do. Your business logic should be independent from data access (for example by use of the repository pattern) and it should be independent from the controller classes (via the use of interfaces f.e.). The model in MVC is the right and only place to put business logic in.
The term model gets kind of overloaded – a few years back (and this is from a Java perspective) people would have considered a model to be more of a simple Javabean (i.e. very basic class with simple getters and setters). However, nowadays, DDD is all the rage (and quite rightly so), meaning that a domain model should ideally contain business methods – I say ideally, as things are never that simple, especially when considering transaction boundaries and persistence.
Great tutorial. I will see if I can integrate some of my stuff with MVC.
That was awesome! I know a little php but am looking forward to using one of the frameworks and this will help me a lot! I plan on combining wordpress and code igniter… hoping for the best! Do you have a better recommendation then codeigniter to combine with wordpress? WordPress will be the cms and the framework will be on the side to pull and edit/create data for a custom search utilizing zip codes. (hoping this could help you in pointing me in the right direction.) Thanks again I learned a ton!
I have no experience integrating wordpress with a framework. Just make sure that you need both. I have read some recommendations to use Expression Engine for that, maybe this link can help:
http://www.derekallard.com/blog/post/are-you-a-codeigniter-using-wordpress/
Great explanation! Very useful for me. thanks.
Good MVC basic details
Nice article. 10x for sharing!
Great article. But I don’t like the fact that the Book class performs the data access. I think it will be better to make another class for that, like BookDAO. The Book class should be only a representation of a book, it’s his responsability.
Best Cake intro so far!
I would choose either CodeIgniter or CakePHP as a framework. Both have a decent community. Best way to learn about these frameworks is by seeing example applications. For CodeIgniter you can see ExpressionEngine, and for CakePHP you can see Croogo CMS: http://croogo.org
An excellent tutorial!!! :-)
Very impressive – you’ve managed to explain MVC really well and in simple, clear terms. Now another interesting article would be comparing MVC to MVP or tiered architectures ;-)
Excellent one to get started with MVC. OOP and MVC are the two most complicated thing for the beginners I guess. Thanks a lot. :-)
Nice primer. Although this highlights how MVC is used in the web world, the actual MVC pattern as defined by Xerox back in the ’70s is a little different.
What you see in the ‘web’ centric MVC pattern is more the MVPC as the view and model are independent of each other. As others have raised above, there is also the question of where your business logic should reside. In the controller? In the model? I say neither, strictly speaking.
IMO there is something missing from this. The model should be your domain representation of the data, and the controller should marshall requests through to the business layer of your application and render the view accordingly.
I thinks its always a good idea to encapsulate business logic in some service/s layer/s that deal with processing the request and updating the model accordingly, and passing state back to the controller.
I highly recommend using MVC in your projects if you are not already. It forces developers to think about separating concerns and generally leads to cleaner, testable and more maintainable code.
It could not be clearer. It’s one of the best intro I read about MVC Framework.
For the one who’s asking about Asp.Net MVC you can look at http://www.asp.net/mvc/learn they have great resources.
And for those who can read in french I wrote an article on why MVC Framework is so great compare to Asp.Net Web Form : http://www.reflexionsweb.info/2009/07/02/ma-premiere-impression-de-asp-net-mvc/
Perhaps this article should be renamed to “MVC for Newbs.” Explanation here: http://www.cad-comic.com/cad/20060823
Great introduction…
The only problem with MVC frameworks, is that programmers loose the fundamentals of the language in which they are programming.
I don’t think you loose the fundamentals of the language, you need to know them to be able to develop your part of the code, but, yes, I agree that the programming world is changing in that sense, not only due to MVC frameworks. Years ago you had to develop complete, huge applications from scratch, building everything with the language. Now you build your application using existing pieces and gluing and extending them with the language. We use JQuery instead of pure JavaScript+DOM, we use CMS to build blogs or sites, we use frameworks and/or lots of libraries to help developing complex applications. We gain a lot, but we need to know a lot of new API’s apart from the language we are using.
Agreed, It’s all about efficiency. Programmers are far more expensive than hardware. What counts is speed of development and maintainability.
Car manufacturers do the same thing. They build five or six completely different cars from one basic platform, and they use two to three engines in a variety of models.
In the real world it just doesn’t make sense to build apps from scratch. You don’t start breeding cows when you want to drink a glass of milk.
Great Primer – a must read for newbies!
Unfortunately, like lot of PHP programmers, who think, they understand MVC, you are wrong.
http://upload.wikimedia.org/wikipedia/commons/2/2e/ModelViewControllerDiagram.svg
Thats why. In your example and diagram, like in thousands examples of MVC, it looks like this:
1. User request for some action.
2. Dispather choosing CONTROLLER.
3. CONTROLLER runs MODEL.
4. MODEL download data from data magazine.
5. MODEL retrieving data and giving it to CONTROLLER.
6. CONTROLLER runs VIEW and giving him return by MODEL data.
7. VIEW are renering ownself.
This is wrong. MVC define, that VIEW is run by MODEL, after download it from magazine, and check if it’s correct.
Yii framework doing this very comfortable (because, when we want imagine it, it hard to do this effectively).
In Yii, we have widgets. When model will get data, Yii create object DataProvider, who will pack concrete model and adjust data. Next, we runs CRUD widget in view, because we should say, how provided data should be render. Off course we can write own cruds widgets.
So, this is correctly implemented MVC.
Sorry for my bad english, I hadn’t practise a lot.
In the original description of the pattern there was a line (communication) between model and view. However, most web development frameworks use a variation of the original pattern and that is why you have seen that in thousands of examples. The tutorial explains this and that’s the reason why the subchapter title is ‘MVC for web applications’.
By the way, if you see it in “thousands of examples”, you may want to try to understand why instead of thinking that everybody is wrong.
@cypherq – I think it’s somewhat futile to discuss how various frameworks or implementations deviate from the pure mvc pattern(that’s pure with a small p by the way). In my opinion MVC is no longer a design pattern in the classical sense as it needs to be implemented differently according to what platform you are developing for.
The most obvious example is the difference between a client-side implementation, like Robotlegs’ MVCS, and a server side solution as discussed in this article. For client-side applications the role of the command tier changes dramatically due to the asynchronous nature of the environment. However, this doesn’t mean that the concept of MVC is lost. The main concern is removing tight coupling between the tiers of your application. If this can be achieved with a different interpretation of the MVC ‘pattern’ than that described 30 years ago for a now defunct language then i don’t see the problem.
I want to see a tutorial for writing own MVC, than just a litte example for cakePHP.
Me too!
I would like to write my own PHP MVC application without frameworks. Only to learn.
Thank you from Brazil!
I would like to see it too…
Have a look at the cake php source – reading source is the best place to start!
Awesome tutorial,
one thing ‘Noob’ is someone that has been doing something for a long time and still hasn’t learn’t anything
where as a ‘Newb’ is a new comer to said something. So in that light your title is a little incorrect I would presume.
Sorry just me..
Thanks again for the tutorial :)
I have to say that the title for this tutorial was “Understanding MVC pattern for web development”. No ‘noob’ reference in the original title :). It was changed somewhere in the way to publishing.
Haha,
I see well thanks for the tutorial good job on it :)
Articles like this make it so much easier for me to get my head around how it all works. Thanks for sharing.
Nice research thank you for sharing
Good one..!!
Great tutorial, explained very well, detailed and clean!
One repeated word: “The code will will be saved as book.php and placed in /app/models.”
Success, thank you!
Good tutorial.
I have a question… where did you get the icon used for the user in the model explanation?
thanks in advance
The user icon is form the icon set ‘Nuvola’. Designer David Vignoni. LGPL Licensed. Thanks for your comment.
Great Tutorial !!!!
Finally I clearly understand the concept !!!
Errm … I’m going to have to change the code for my latest project … T_T
Nice Tutorial! I liked the way you presented examples on the 3 components that comprise MVC.
very nice MVC stuff :) and love to work with CodeIgniter
I can’t tell you how much I appreciate this article. I’ve spent the last week researching MVC in hopes of applying the concept to a development platform that I work in. Most information on the web is overly technical and abstract (e.g. Wikipedia) or spends too much time showing how it is done in a particular language or framework (which is lost on me.) This article had a great balance of theory and application. Even though it uses cakePHP to demonstrate, the examples were simple and explained well so I was able to follow.
Just wanted to add a thank you for your article. Your article was clear and concise and very easy to follow.
Thanks again!
That was very clearly tutorial for noobs like me. :)
Thanks.