Understanding MVC: The Basics

October 8, 2009 — 24 Comments
The Yii Book If you like my writing on the Yii framework, you'll love "The Yii Book"!
This entry is part 1 of 3 in the series Understanding MVC

I’m planning on writing several posts on the Yii framework (for PHP 5), which I’ve been using for the past several months. Before getting into that, though, I thought it’d be worth while to write about the MVC—Model-View-Controller—architecture first. MVC (first defined 30 years ago!) has become a standard approach for frameworks and many other types of application development, where the emphasis is on separating presentation from logic. By taking this route, you can more easily tweak individual parts without (hopefully) breaking the whole.

The basic concept is relatively simple to understand, but I found that the actual implementation of the pattern can be tricky. In other words, it can take some time to master where you put your actual code. In this post, I write about the individual pieces and how the relate to each other. In a follow-up post, I’ll write about how to communicate between them, and what in the world $this means at any particular point!The MVC pattern breaks an application into three distinct parts:

  • Model, which represents the data
  • View, which is the interface (i.e., how the user interacts with the data)
  • Controller, which are the actions

I think the Model is easiest to comprehend as it’s the data being used and manipulated. Models are often tied to database tables, where one instance of a Model represents one row of data from one table. Note that if you have two related tables, like employees and departments, those would be represented by two separate Models, not one. You want to keep your Models as atomic as possible. A less obvious, but still valid, use of Models is for representing non-permanent pieces of data. For example, if your site has a contact form, that data won’t be needed after it’s emailed out, but must be represented by a Model up until that point (in order to perform validation and so forth). Models not only represent the data, but common manipulations of that data, from validation routines to altering the data (e.g., stripping the HTML tags out of submitted text).

Views are also straightforward when it comes to Web development: Views contain the HTML. Most frameworks I’ve used (I’ve had the most experience with Yii, Zend, and Ruby on Rails), use a page that acts as the primary layout. For example, that page would start and finish the HTML. Other View pages represent aspects of the interface, such as a form, a listing of multiple records, or the display of an individual record. Those individual pieces are then brought into the primary layout file to generate the complete output.

If you have a classic employees-departments application, you might have these View files:

  • Primary layout for the employees pages
  • Form for adding and updating employees
  • Listing of all employees
  • Display of all the information for a single employee

There would be complimentary pages for the departments section, too, possibly including a variant on the primary layout that’s particular to the departments area.

Views don’t just contain HTML, however, they must also have some PHP (or whatever language). Such code should only perform very simple tasks, like printing the value of a variable. A common beginner’s mistake is to put too much programming (i.e., logic) into the Views. The goal in a View is to combine the data and the presentation to create the interface. Views shouldn’t be “thinking” much. For example, a View would likely use a conditional so that it only prints a variable if it has a value, or use a loop to print out every member of an array, but a View should not do serious formatting or alterations on the data. Say you have a page that also displays how long the logged-in user has been registered on the site. The original registration date would come from the database (i.e., be part of the Model) and the resulting calculation would be displayed in the View, but the actual calculation should take place in the Model, not the View (or the Controller).

A Controller often acts as the glue between the model and the view, although it’s not always that clear. (In fact, the MVC distinctions can easily be blurred.) As I said, a Controller represents actions: things done with Models and things done with Views. Model actions include the retrieving of a single record from the database or the retrieving of all the records. View actions are responses to user events: the submission of a form, the loading of a page, etc.

To put this all within a context, a user goes to a page like www.example.com/index.php/employee/list (the formatting of URLs is a different, but related subject). This might trigger the “list” action within the employee controller. That list action might invoke a “retrieve all” action, which gets all of the data from the Model. That list Controller action then passes that data to the “list” view, which uses a loop to display all of the employees within the layout of the site.

And that brings me to some actual code, which I’ll show in a subsequent post (hopefully in two days). EDIT: Here’s the link to part 2!

If you enjoyed this post, then please consider following me using your favorite social media, the RSS feed, and/or by subscribing to my newsletter. Or go crazy, and buy one or more of my books . Thanks!

24 responses to Understanding MVC: The Basics

  1. Thanks for this … looking forward to explanation of the “employee/list” portion of the url.

    John

    • You’re quite welcome. Thanks for the feedback. I’ll address the URLs and how they relate either in part 2 or I’ll a third part to the MVC discussion.

  2. I can’t wait for the next post!

  3. Finally, someone explaining clearly the C of the MVC. I have been programming in PHP for 9 years and have been looking at frameworks for a few weeks now to try and decide if I should/could use them.

    I decided on Yii (for a lot of the same reasons you listed in a previous blog post back in June) but was still trying to make sense of the whole MVC paradigm. Being used to a single-tier web app, trying to separate “what goes where” for the MVC was becoming a nightmare and leading me to giving up on frameworks altogether.

    Now, maybe with some “clear layman talk” about the MVC framework and your upcoming part 2 I will be able to finally put to use what I am pretty sure is something I can make use of in a real way.

    Thanks.

    • Thanks for the feedback. Yes, I also found, when starting to do MVC programming, that it was never clear to me where I was to put something. My first attempts at using a framework resulted in way too much experimentation!

  4. Larry,

    Glad things seem to be stabilizing!

    In learning PHP, I discovered Yii and my intuition told me it was the best framework for me. Along the way I also recognized MVC as my route of choice. The trouble is that, as a new framework, Yii is weak on documentation. Additionally, the weird introductory Yii video on the Yii site, with the odd ‘Yiihaa’ sound and animation, made me concerned that this may be a framework that may not take off. In contrast, CakePHP has a really nice landing page and documentation structure. My hunch is that Yii is better under the hood, but it’s a pretty beat up hood right now.

    The wind up is that I’m thrilled you’re going to be educating about Yii as I really want to utilize it more than CakePHP. So thanks for getting into that — and MVC architecture as a whole.

    • Thanks, Patrick, for the nice words and for your input on this. You’ll be happy to know that I just wrapped up the next post on Yii, to be published tomorrow. I should say that I’ve never used CakePHP, but have heard great things about it, so I don’t want to disparage that alternative. And yes, the Yii documentation is more sparse, even still several months after I first started using it, but it seems to me that it works well enough on its own not to require more documentation. But documentation is crucial, so I do hope it improves, and will do what I can to help towards that end. I will note, though, that there was a TON of documentation out there on the Zend Framework, and it still didn’t help me understand it that much. Or when I did come to understand it, I just didn’t like it all that much.

      Another argument for Yii, to make up for its young status, is that it was created by the person that made the popular Prado PHP framework. So it’s not a first framework by someone and there’s some solid people behind it. Plus, I’m sure they came to this with the knowledge of how they can make a better framework. They also seem to be putting out just about monthly releases, a combination of bug fixes and minor new features. So that’s a good sign.

      Thanks again,
      Larry

  5. I am confused that you state “but the actual calculation should take place in the Model, not the View (or the Controller).”

    I thought the controller does the actual thinking and calculations?

    • Good question. To clarify, Controllers do actions in terms of responses to users: click a link, do this; submit a form, do that; etc. So Controller actions are in a broader sense. Models are the data, and something like a calculation based upon part of a Model is therefore tied to the Model, not to a Controller or a View. By doing it this way, the same information could be used in lots of Views. And again, think of Controllers as controlling user actions. Does that make more sense?

  6. Yes it does make more sense now. Thank you!

  7. maybe i’ve overlooked it…so forgive me…but did you ever get around to covering: “…and what in the world $this means at any particular point!”??

    Thanks!

    • Well, I’m not sure, but $this in OOP always refers to the current object. So in a Model definition it refers to the current instance of that Model. In a Controller definition, it refers to the current instance of that Controller. In a View definition, it refers to the current instance of that View.

  8. @v.m.p you might find the back and forth on the object operator ‘->’ interesting, especially given your question about $this, here is the discussion on Robert Gonzalez’s website:

    http://www.robert-gonzalez.com/2009/03/04/php-operators-double-and-single-arrow/

    I loved it that rasmus even chimed in at one point.

    The $this operator is a ‘special variable’ used to “refer to the currently instantiated object.” ‘$this->name’ where name is a variable defined in the class template that creates the object.

    What I find particularly special about $this-> is without it, how would an ‘object’ refer to itself?

  9. Hi Larry,

    Thanks for posting such a very good article about MVC now i’m clear about MVC and i’m also looking for some good coding examples on MVC so plz post any article included MVC programming example. again big thank you and virtual hug…. :-)

  10. Thanks a lot Larry ! I think this is THE BEST explanation I came across !! Great job !!!

Trackbacks and Pingbacks:

  1. Berkenalan dengan Yii Framework BeBeTe.name - January 23, 2011

    [...] sewaktu mempelajari CakePHP untuk pertama kalinya. Sebagai rujukan, artikel dari Anant Garg atau Larry Ullman menjelaskan MVC disertai contoh yang mudah [...]

  2. Stephen Reid Design » Yii-ppeeee! - February 17, 2011

    [...] include Ruby on Rails and CakePHP). Lucklily for me, technology writer Larry Ullman has an excellent article introducing the concept of MVC, which if you are interested in using Yii yourself, I highly reccommend you read [...]

  3. Learning the Yii Framework 1 / 8 | 웁스교교주의 이야기 - July 15, 2013

    [...] 탐색할 수 있습니다.(여긴 없어요 – 역자 주). 혹시 관심이 있으시다면 MVC 구조에 관한 저의 포스트도 [...]

  4. How To Be PHP Programmer And Yii Expert In 14 Days | ansaworks - January 30, 2014

    […] Learn MVC http://www.larryullman.com/2009/10/08/understanding-mvc/ […]

Comments are great, but I'd strongly prefer any requests for assistance get made in the support forums. Thanks!