Monday, February 18, 2008

MVC and you: Partners in Freedom! (Why developers should be using Model View Controller architecture)

“Model/View/Controller”. To some people, it seems to be nothing but a buzzword – an ambiguous term tossed around development forums and blogs; an idea that’s vague and confusing to anyone who hasn’t actually delved into MVC development. To others, MVC is an obvious way of organizing application structure, and there’s nothing new or exciting about it. And finally there are those of us who stumbled into MVC enlightenment almost by accident and realized, wide-eyed and drop-jawed, that it’s just the “right” way to build applications.

Consider me part of the third group. It wasn’t all that long ago that a Ruby on Rails-enthusiast friend of mine insisted that I start moving toward MVC development for the multitude of PHP projects I’m involved in. He knew I was working on a new PHP framework, and, thankfully, he was persistent in his endeavor to get me to delve into MVC sooner rather than later. My framework had the DB abstraction layer. It had the template system and the form validator and the photo handler and the AJAX module. But what was really missing was a way to tie it all together, and once I got about 20 minutes into MVC, I felt disappointed in myself for not having seen the light earlier. It just makes sense to develop within the MVC structure, and in this article I’m going to first give an introduction to what that structure is, then touch on a few reasons you should be using it, and finally describe a few hurdles you can expect to have to overcome while getting accustomed to it.

What is Model / View / Controller architecture ?

Model/View/Controller, or MVC, is essentially just a way of structuring application code. The idea is not new (it’s been around since 1979 according to Wikipedia), but it’s only happened fairly recently that MVC started to gain widespread acceptance as a viable way to develop web-based applications. A lot of the charge toward MVC-based web development was led by Rails, the Ruby framework that has gained significant momentum in the past few years.

MVC-based web development is based primarily on the “M”, the “V”, and the “C” themselves – the data Models, the presentation (or View), and the interface between them – the real workhorse - the Controller. Each component has a specific role, which I’ve outlined below:

1. The data Model is used to store and retrieve information from the database. In most MVC frameworks, a data model class will exist for each of your database tables. Because the model extends a parent class that has very robust, often clever functionality, you can often gain application-level access to your data (e.g. $employee->first_name) with only a few lines of code. Data models can also be related to one another just as their underlying tables are related, which provides even greater functionality when accessing data across tables (e.g. $company->employees->fetch_all()). This extensible, customizable method for mapping tables to objects allows you to access your database without necessarily having to write SQL. Basic read and write operations are performed through simple class members and methods, and even more complicated queries can be done without having to manually write SQL, though that option is always available.

2. The “View” in Mode/View/Controller is the presentation layer that contains the content the end user will see. In web applications, the view will contain your actual HTML tags. Using the features of the templating system included within the application framework, you can add dynamic functionality to the HTML output while still keeping the application code and the presentation separate. Such a separation allows for cleaner code in both the scripting language and the HTML, and it allows designers and programmers to have more independent control over their respective parts of the application development.

3. The Controller is, as mentioned above, the workhorse of the application. The code in the controller is what’s actually run when a page is loaded, and it handles the “pull and push” – taking data from the database via the data models, passing that data to the view, then rendering the output. In most web-based MVC frameworks, specific URLs are attached to specific controller and methods through a routing file, so, for instance, “/Blog/View/123” might call the view() method of a BlogController object and pass it the id of 123.

Sounds pretty complicated. Why switch from my tried and true methods of inline scripting?

One of the greatest pitfalls a developer can succumb to is using only the language, tools, or methods he or she already knows in order to accomplish a task, rather than seeking out and utilizing the best tools for a particular project. A little bit of time spent overcoming the learning curve can often introduce efficiencies, expand your skillset, and actually save a significant amount of time in the long run.

Many web developers have fallen into the trap of writing what can really be described as a collection of scripts, rather than developing a cohesive application, because the former is the way most of us were introduced to web development. The most common architecture used in, for instance, PHP development, doesn’t really qualify as an architecture at all. Most commonly, PHP-driven sites are comprised of a handful of individual script files that each handle incoming data from web forms or display data pulled from a database, but together lack any kind of standard structure. While this method is quick and dirty and works well for smaller applications, it simply does not lend itself to creating scalable, modular solutions that can be easily maintained and updated even as the size of the application grows.

MVC provides a very structured but very versatile approach to web development, lending itself to being immediately scalable while providing simple interfaces to common functionality. Consider how often your application needs to perform the same types of operations on different data – often this is referred to as CRUD: Create, Read, Update, Delete. Entire websites and web-based applications can often be accurately described as offering only these four features, operating on different data. Without a framework to provide CRUD functionality, the developer has to hand write his INSERT, SELECT, UPDATE, and DELETE queries manually, not to mention coding tedious input validation methods to ensure security and data integrity. However, any MVC framework worth its salt will provide all of that functionality in just a few lines of code. Interested yet?

Ok, you’ve convinced me, but what kind of learning curve can I expect?

The first thing you should know about MVC development is that everything is done through objects, so a solid understanding of object orientation will be extremely helpful in moving forward with any MVC framework. Additionally, HTML output is handled via templates (views) – you will almost never see HTML and PHP in the same file when doing MVC development. Instead, data is passed to the template (sometimes automagically, sometimes manually) and is accessed through special syntax (e.g. <{myvar}>) in the template itself. The separation of application code and presentation sometimes throws people off initially, but the benefits of this method become apparent very quickly. Finally, with MVC, you will not see your .php files in the URI the way you’re used to seeing them. Instead, you define a route that points a URI to a specific method in a specific controller. For instance, might call the show_list() method of your BlogEntryController. Not only does this kind of URI routing offer almost limitless customization as to what your URI will look like, it can also be used as an SEO (Search Engine Optimization) tool.

Which framework do you recommend?

Personally, I use FUSE ( However, that’s a bit of a shameless plug, since FUSE is my own framework. (See the video below for how you can build a database-driven web app in about 5 minutes :-) Having worked with other frameworks, I honestly believe that FUSE is the easiest MVC framework for PHP, especially as far as initial entry is concerned. There are a slew of other great frameworks available, however, including Cake and Symfony for PHP, Rails for Ruby, Grails for Java, and many, many more.


Anonymous said...

I'm not new to the MVC paradigm - I have experience with codeigniter and akelos.
Your framework looks really good - I'm going to use it for my next project. thanks

Anonymous said...

OH NO!! Not another new mousetrap to keep trying to re-invent...and developers STARVE to death, and never catch a mouse...laugh