|By Joe Rinehart||
|April 13, 2005 12:00 AM EDT||
I saw a one-man band once, and it was quite a sight. He had a bass drum on his back, operated by a cog attached to one ankle, thumping as he stomped his foot. Shoestrings tied to the neck of his guitar would move drumsticks attached to a snare drum perched atop the bass drum.
Another string attached to his right elbow operated a cymbal clamped to the side of the snare drum. I spotted duct tape in more than one place. It was a little complicated, and changing anything was bound to affect everything else.
Does this sound like an application you may have worked on? I'll admit it: it sure sounds familiar to me.
Now, I've also seen some very good orchestras. The conductor runs the show. She doesn't necessarily know how to play the viola or the sousaphone, but she knows how to use her musicians, and trusts them to do their jobs.
I don't know about you, but I'd much rather be a conductor. My musicians could change how their instruments worked, but as long as they still played in tune, it wouldn't matter to me. More importantly, I can add new instruments without having to learn to play them or figuring out how to tie, clamp, tape, and/or tack weld them into place.
That's a powerful paradigm, and this power is what the Model-View-Controller (MVC) design pattern gives you.
What Is Model-View-Controller?According to James Dempsey's "Model-View-Controller Song," MVC is a way of organizing your code into "functional segments so your brain does not explode." MVC divides your application into three layers, each with a clearly defined task:
The Model contains all of the business logic and data in your application. It is not a stretch to say that your Model literally is your application. Typically, a Model consists entirely of objects or services such as CFCs, Java classes, and / or Web Services. A Model never has any knowledge of Views or Controllers.
A View is what the user sees, and is how the user interacts with your application. The View's job is to allow user input and display the "state of the Model," an Object-Oriented (OO) way of saying "your application's data." Most often, Views are traditional ColdFusion pages (.cfm). Other mediums such as Flash can also act as views. Because your Model isn't aware of the Views, you can interchange views without affecting your overall application.
The Controller is simply "glue" code that passes data back and forth between the View and the Model. The Controller takes data from the user, such as form data, and gives it to the Model for processing. The results are then given back to the View, which is shown to the user.
While some users of MVC may object to passing the data back through the Controller, it's a common way to implement the MVC pattern in a Web environment. In a desktop application, however, the View might be allowed to ask the Model for its state information directly. However, because of the nature of the Web, it's a lot easier to simply "push" the state information into the View through the Controller.
Why Use Model-View-Controller?I'm sure we've all heard talk about separating "business logic" from "presentation logic," and MVC does exactly that. By putting the Controller in between the Model (business logic) and View (presentation), we're insuring that they're not only separate, but highly reusable because they're not specific to a particular implementation. Additional Views can use the same Model without any modification. More importantly, the internal working of the Model can change without affecting the Views. This should sound familiar: we've arrived at the power described earlier when I said I'd rather be a conductor than a one-man band. Let's revisit what I said earlier, but change a few words:
"My components could change how their internals worked, but as long as they kept the same interface, it wouldn't matter to me. More importantly, I can add new components without having to learn how they work, just how to use them."
That's a very powerful statement to make about application design. Model-View-Controller utilizes Object-Oriented Design concepts known as "decoupling" and "separation of concerns" to achieve this power. In a "traditional" ColdFusion application, each page is responsible for a good deal: business logic, data access logic, presentation logic, and data validation. By isolating the business logic in the Model and the presentation logic in the View and having the two communicate through the Controller, we've "decoupled" the business layer from the presentation layer. Each of the three layers has a responsibility, or "concern" that is separate from the others. As long as the boundaries along which the layers communicate, or "interfaces," remain the same each layer can change its internal functionality without affecting other the other two.
Let's Code: An MVC ExampleBuilding an MVC application in ColdFusion isn't very hard. You'll just need a good understanding of ColdFusion Components (CFCs) and an open mind. If you're not up and running with ColdFusion Components, you may want to read Jeffry Houser's article entitled "ColdFusion Components" when you're through with this article (CFDJ vol. 6, issue 11).
First, we need a problem to Model. For a fun example, I've chosen to Model translation of English phrases into Pig Latin. For our first attempt, I'm implementing a very simple version of Pig Latin - for any given word, move all consonants until the first vowel to the end of the word, and then add "ay." For example, "Model-View-Controller" becomes "odelMay iewVay ontrollerCay."
It's easy enough to encapsulate all the logic for this into a CFC. Listing 1 shows the entire model for our application, contained in PigLatinizer.cfc. You'll see that it has a single method ("Translate") that receives a string, and returns a translated string. At this point, we have a working "Model" of our "problem domain" - translating phrases into Pig Latin.
Now, we need a View to interact with our model. Listing 2 shows our basic translator form. It has a form field that collects a phrase to translate, a submit button, and will optionally show results of the latest translation.
Well, that was easy. We have a Model and View. Now we need a Controller to glue the two together. One approach many have taken is to simply add pseudo-Controller code to the top of their View pages, closely mimicking the standard self-posting form architecture ColdFusion developers have used for years. However, this places the Controller code in your View, eliminating any chance of re-use. Instead of doing this, we're going to use a CFC called PigLatinController. The source code for PigLatinController.cfc is shown in Listing 3. Examining the code reveals that it's pretty simple. There's an empty constructor ("Init") and a single method ("Translate"). While our constructor here remains empty, in the real world, this may be a place to insert information, such as datasource names or other configuration data, that the controller will need to pass along to the Model.
Examining the Translate method shows a controller in action. It first creates the needed portions of the model - in this case, simply an instance of PigLatinizer.cfc. It then passes data from the View (form.phrase) to the Translate method of the PigLatinizer. The user is then redirected to the view, with the resulting translation passed as a URL variable.
Now we have a Model, a View, and a Controller. What we're still lacking, however, is a way to have them all "talk." This is a where a framework is needed.
Building a Simple FrameworkWhile there are two popular frameworks available for what we need to do (Fusebox and Mach-II), we're going to build our own mini-framework using about ten lines of code. It's going to be bare-bones, but it should get the job done while also introducing the need for more robust, application-agnostic frameworks.
Listing 4 shows our Pig Latin's Application.cfm file, where lines 3 - 13 represent our framework. First, we see if the application is initialized. If it's not, we create an instance of our Controller, placing it into the application scope. Second, we examine the URL scope to see if a parameter named "method" exists. If it does, we CFInvoke that method of our controller.
Running Our ApplicationWe've now built a complete MVC application for translating phrases to Pig Latin. Let's step through two page requests, initial and form post, to trace how the pieces of MVC work together.
Initially, the user requests Index.cfm. ColdFusion processes the Application.cfm file. Our framework insures that an instance of PigLatinController (the Controller) exists in the application scope, and then looks for URL.Method. Because URL.Method doesn't exist, no action is taken. Index.cfm (the View) then presents the user with the appropriate form.
The user then enters a phrase and clicks the submit button, and our next request cycle begins.
Again, ColdFusion processes the Application.cfm file and insures that our Controller exists. This time, however, URL.Method is defined, and its value is "Translate." Our mini-framework recognizes this, and invokes the "Translate" method of the Controller.
Inside the Controller, the "Translate" method creates an instance of PigLatinizer (our Model). It passes the data from the View (form.phrase) into the Model's "Translate" method, and collects the result. The Controller then CFLocates the user back to Index.cfm, appending the result of the translation to the URL. Index.cfm, the View, shows the "state of the model" (the translated phrase), and dutifully re-displays the translation form.
Modifying Our ApplicationBecause we've placed the Controller between the Model and the View, changes to the Model won't affect the View, and vice versa. Realizing our implementation of Pig Latin isn't complete and that there are additional rules for handling words beginning with vowels, we need to modify our Model. Luckily, there's a freely available Java class that translates English into Pig Latin. We can modify our Model to use this class instead of its own internal logic (Listing 5 shows this modification). Because we're only changing its internals, and not altering its interface, the rest of our application will remain unaffected. By isolating our changes, and decoupling our business logic from our presentation logic, we've given ourselves a both more powerful and safer way to alter or scale our application.
The Need for FrameworksOur bare-bones framework is fine for our Pig-Latin translator, but I wouldn't want to develop an enterprise application with it. On a low level, the method of processing input in the controller then CFLocating would make it hard to return meaningful validation results - the URL string could become huge! On a higher level, what if one method of the Controller needed to call another method? It'd be easy to add the code to do so, but this may begin to fall outside of the "concern" of the controller (passing data between the View and the Model) and may begin to fall into the realm of business logic or application design. Frameworks such as Fusebox and Mach-II help out in this problem. By removing this control of "flow" from the Controller and letting you organize your application using XML, they both allow the Controller to assume its proper role of passing data. Frameworks have a number of other advantages, but that's another article.
SummaryModel-View-Controller is an elegant way to divide your application into logical layers. Each layer has a single job, and does it well. The Model represents your application's business logic. The View presents data from the Model, and accepts user input. The Controller serves to pass data between the View and the Model. Most importantly, the Controller serves to decouple the View from the Model, isolating what changes to bring unprecedented power to your application's design.
Further ReadingThis article provided a high-level introduction to Model-view-controller. Hopefully, it's gotten you interested in using MVC to simplify and enhance your application designs. However, it's glossed over a good deal of Object-Oriented concepts and terminology. There's a lot to learn about the theory of MVC and the various design patterns that are used inside of it (MVC is technically a "compound" pattern, made up of other design patterns).
If you're ready to jump into using MVC for ColdFusion applications, I'd begin by taking a look at the Fusebox (www.fusebox.org), Model-Glue (www.model-glue.com) and Mach-II (www.mach-ii.com) frameworks.".
|Derek 05/04/05 10:45:24 AM EDT|
Where is the sample code for this?
- Where Are RIA Technologies Headed in 2008?
- The Next Programming Models, RIAs and Composite Applications
- AJAX World RIA Conference & Expo Kicks Off in New York City
- Constructing an Application with Flash Forms from the Ground Up
- Building a Zip Code Proximity Search with ColdFusion
- Personal Branding Checklist
- CFEclipse: The Developer's IDE, Eclipse For ColdFusion
- Has the Technology Bounceback Begun?
- i-Technology Viewpoint: We Need Not More Frameworks, But Better Programmers
- Adobe Flex 2: Advanced DataGrid
- Cloud People: A Who's Who of Cloud Computing
- Web Services Using ColdFusion and Apache CXF