MVC for Noobs
basix

MVC for Noobs

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!

Tags: basixmvc
Add Comment

Discussion 99 Comments

Comment Page 2 of 2 1 2
  1. Jam says:

    I still don’t quite understand the purpose of MVC. The separation of logic gets to a point where it becomes illogical and tedious. I’ve tried to get into a framework to work my way into MVC many times, but each time I do this I find myself annoyed with the sifting through endless directories to accomplish simple tasks. Would anybody care to enlighten me? Because this article certainly did not.

    • Thomas Slade says:

      Jam, I completely agree with you on smaller projects. Why bloat a project that doesn’t need it?

      Then again it provides a standard for larger projects and helps developers work together and follow conventions. Separating logic from look-and-feel can keep designers from tampering with code and speed up the debugging process.

    • SolidSquid says:

      From what I understand, there are three big advantages to this approach. Firstly, if you’re working in a larger team it makes it much easier to find sections of code developed by other people. This makes managing development of large scale projects much easier, as the developers should be able to find the section needing changed or added to fairly easily.

      The second is further down the line, when you need to do maintainance on the code after having worked on other projects. If you have a well defined, standardised structure to the application, it should be fairly easy to get back up to speed with it and start coding away again if you have to revisit it later, either to upgrade it or to fix bugs.

      Thirdly, since it’s a standardised object orientated model, it should be fairly straight forward to port code from one project to another. This means that the longer you work with the framework, the larger the range of features you can offer your clients, since even code from your first site with the framework should be compatible

      Anyway, as a result of both of these, MVC frameworks are getting pretty popular in larger scale development environments (I know when I was looking there were a bunch of places looking for Zend experience), since it means if they build something it’s both re-usable and easily maintained (fortunately for them but less so for us, even if the original developer is no longer employed). The up side for developers, apart from easier to maintain code, is that the frameworks are somewhat standardised. As a result you can move from one place using an MVC framework to another and get a decent understanding of their code base fairly quickly, which is quite a selling point during a job interview

  2. erphan says:

    Thank you for your tutorial. This is a better tutorial because you make the real application sample and make me more understand in my way for mastering the MVC. But some missing one: you dont include how design the database/table data.
    Finally always thanks a lot for this tutor!

  3. sarmenhb says:

    i’ve found it much easier to just sit down and create my own framework. i am not sure if it fits into the mvc category but it does the job real well. so anytime a project comes in that the client needs both the front end and a backend to be able to manage their website such as a cms. my job is alot easier i have a few plugins such as jcrop, or product purchasing and i just copy the folder or files into the app and link it in making me finish a whole lot faster. public mvcs are good for when you are working in a team and everyone can understand the language or objects in the code. if you are doing each and every project from scratch and cant understand why you are taking so long, there you go. sit down and make a framework , something that you know that you will be using again and again to save alot of time.

  4. Paul says:

    Great tutorial! You really break down for a noobie like myself. Understanding the concept of MVC is crucial in web application development.

  5. Kris says:

    Nice tut Pablo — keep up the good work!

  6. rasnier says:

    Hi,

    I am working with MVC in my thesis proposal Online Enrollment System. Can I ask help in this forum? That will be a great help for me. Thank you and God Bless.

  7. rasnier says:

    …I forget to mention i am a novice in programming… hope you could help me out here… JUST REALLY TRYING my best and hoping I could find help in here..

  8. Daz says:

    I started my IT career in the ’60′s. Devising a structure was and still remains the only way to control development. Separating tasks out between display (it was only print outs back then*), data and logic to apply was the simple start point which then developed into more formalised structural approaches. Even when doing simple tasks do not be sloppy – create and adhere to structure or if you prefer task segmentation whatever you want to call it. This article is well written showing the priciples clearly. Frameworks are doing a lot of the decision making for you, so embrace.

    * not strictly true as we also devised simulations of real processes driving clocks, control panels, producing ‘work’ tickets, etc.

  9. Finde says:

    Good Job!!

  10. webdev says:

    Very bad tutorial.

  11. Sub says:

    Absolutely fantastic post. Learnt a lot within 10 mins that would have taken me days to learn using a book.

  12. SolidSquid says:

    Great overview of MVC, makes a lot more sense now that I’ve read through this. Even just the Model-Controller-View diagram made more sense than the others I’ve seen. Going to be spending some time tonight seeing how I get on with the CakePHP framework (or maybe Zend if I can find some tutorials, seems to be more companies working with it)

  13. Ariel says:

    Excelent explanation. This model MVC, in beetwen others characteristics, facility to scale in large projects, the documentation, optimize the costs and improve the technics of development.

    Thank.
    Great of the Argentine.

  14. karthik says:

    Thumbs up!!! It would really helped more if there was explanation on the DB Access

  15. Oliver says:

    Holy crap dude, THANK YOU for helping me understand what MVC is about. I started learning php like two weeks ago and I was so confused when people started creating these extra directories. Yes, I can understand why you want to separate view and the php code. That makes absolute sense, but then controller and model difference was confusing! Also the tutorials I read kept calling more controllers within the central controller so that only lead to more confusion.

    But now I have a much better understanding. I’m very happy you choose a popular PHP framework to demonstrate how MVC works. You went above and beyond here, not just giving an abstract idea, but gave a diagram and real world popular MVC!

    Please continue to write the way you do.
    Thank you again.

  16. Anele says:

    You know what !!!! the only problem I have with Frameworks is that it does not get into detail as to what is happening. they just tel you how to build a blog. take cakePHP for instance… I cold not understand anything at first as what I was doing..

    Another thing is that they always tel you to read the manual. It was very difficult for a beginner who only know sphp from reading online tutorials. http://www.tizag.com/phpT/

    but non-the-less I found a book. http://www.amazon.com/Beginning-CakePHP-Professional-Experts-Development/dp/1430209771

  17. carl says:

    this wasn’t a good tutorial for “noobs”. I’m still searching.

  18. Olu says:

    Thanks. It was excellent overview of what MVC is all about. The explanations and real life examples of each of the components and the visual diagrams as well were fantastic. I won’t be using php myself (I’ll be using good ol Visual Studio ) but you’ve given me an understanding of the whole concept of MVC.

  19. Jayanti Roy says:

    Very good introduction for Noobs.

  20. Maheswar Reddy Yarramreddy says:

    Its really good article to help the beginners of JAVA…..

  21. Eric says:

    Great read! Have a project that was built using MVC framework and this helped quite a bit in helping to understand the logic behind it. Now to dig into CakePHP a bit more and their docs. Great read for beginners just trying to crack the sacrifice, thanks! Can see how it would help cut out a bunch of the garbage and repetitive code in larger scale projects:)

  22. Himitsu says:

    Greetings! Your Tutorial is worst messy I ever seen! Here we are talking about dummies. who don’t even know how a mvc works! You explain on cakephp as example, which is incoherent for us! Use a self made mvc as example! This will help us to understand this better! One more fact, use a mind print to explain your schema! Thank you Bye!

Comment Page 2 of 2 1 2

Add a Comment

To add a code snippet to your comment, please wrap your code like so: <pre name="code" class="html">YOUR CODE</pre>. You can replace the class name with "js," "css," "sql," or "php." If there are any "<" or ">" within your code, please search and replace them with: &lt; and &gt; respectively.