Showing posts with label rails. Show all posts
Showing posts with label rails. Show all posts

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, mysite.com/BlogEntries/List 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 (http://www.phpfuse.net). 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.




Friday, December 28, 2007

My favorite web tools of 2007

As the year comes to a close, I thought it would be fitting to reflect on what development tools helped make 2007 easier for me. These tools weren't necessarily created in 2007, but as someone who has a tendency to want to re-invent the wheel, I previously found myself overlooking great third-party products and ideas, so consider this a thank you to those people who contribute great, free code to the community.

1. Scriptaculous (http://script.aculo.us)
Provides: Easy drag and drop, animation, and AJAX functionality

Building on the Prototype Javascript framework, Thomas Fuchs, with the help of a community of open source contributors, has given us an easy-to-use but extremely powerful toolkit for some of the more tedious Javascript tasks we face - namely UI features (e.g. drag and drop) and AJAX functionality. Those of us who have been around long enough to have had to work with positioning and controlling user interface elements know the headaches involved in getting your event handlers to fire as you expect them or tracking the x and y coordinates of the mouse. In fact, I suspect the #1 most common reason for keyboard smashing and monitor punching among developers goes something like "graphic element expanded beyond its container instead of properly wrapping to the next line".
With Scriptaculous, implementing drag and drop, including sortable lists, is about as easy as it can feasibly be, and the AJAX-related classes are a godsend. Even someone with only moderate experience in javascript should be able to implement advanced UI features and AJAX functionality without much trouble. Scriptaculous is well integrated with Ruby on Rails, and I expect that it will soon be driving a lot of the AJAX functionality in my own PHP MVC framework, FUSE

2. The Free Rich Text Editor (http://www.freerichtexteditor.com/)
Provides: a full WYSIWYG editor, a la blogger's "compose" feature

Definitely file this under "things I would NOT like to have to write from scratch"! Released under the Creative Commons License (thankfully), this rich text editor control allows you to easily implement full WYSIWYG functionality into your web application. With a wide range of editing functions, from bulleted lists and visual color selection to drag and drop image placement, it just doesn't get any better than this. A simple .js configuration file provides you with customization options, and once you add in a few tags, you're all set. Custom WYSIWYG in under ten minutes. This one has been integrated into FUSE since the day I found it!




3. Model / View / Controller architecture
Provides: Sanity

Ok, this isn't exactly a "tool", and the idea has certainly been around for a long time (since 1979 according to Wikipedia) , but MVC has finally started to gain real acceptance in the web development community to the point where it's becoming the standard for large scale, web-based applications. Due in some part to the popularization of Ruby on Rails, along with other MVC frameworks like Cake, Symfony(, or FUSE), web developers have finally started realizing that procedural scripting, especially the sort that mixes application code and presentation (e.g. PHP and HTML in the same file), isn't the best method for creating scalable, manageable applications. At this point, most MVC developers will look at you with a true sense of confusion and disappointment if you suggest ANY other way of developing a web app, but it seems that the majority of web programmers are still stuck in the "Chapter 1 of 'Building your first PHP applicatoin'" mentality, mixing procedural code in with HTML and packaging it all up in ugly URLs with long query strings. Get with the program, guys!


So there you have it - some things that helped me keep what's left of my sanity for the past year. I may add to the list if I think of something that really needs to be mentioned, but the three items listed were part of my daily development life in '07, and I suspect that all of them will keep me company for '08 as well.