Basic MVC is a Gateway Drug
posted under category: ColdFusion on February 24, 2010 by Nathan
My last blog entry was about how to create the easiest ever MVC application, but looking at it, you have to see where you'll just start repeating things all over the place. I mean, look at this code:
/app/controller/main.cfm
<cfinclude template="../model/main.cfm" />
<cfinclude template="../view/main.cfm" />
Are we going to have to do that for every controller? That's some serious boilerplate stuff that really shouldn't have to be typed every time. What a pain that would be!
So lets see what we can do to fix that. What we need is a generic controller that will do most of the job, most of the time, but allow us to do special work when we need it. I hate to use the "F" word, but I'm going to - this is a Framework. Worse yet, it's your standard run-of-the-mill front controller framework. I know, I hate it too, but hear me out.
There's a real easy, real obvious reason for doing it like that. No, I'm really not a fan, but I do it all the time, right along with everyone else. Let's see what it takes to make our MVC quasi-framework happen.
/app/controller.cfm
<cfparam name="action" default="main" />
<cftry>
<cfinclude template="controller/#action#.cfm"/>
<cfcatch />
</cftry>
<cftry>
<cfinclude template="model/#action#.cfm"/>
<cfcatch />
</cftry>
<cftry>
<cfinclude template="view/#action#.cfm"/>
<cfcatch />
</cftry>
Now hitting /app/controller.cfm?action=main includes the main controller, model and view automatically, and if they don't exist, it just ignores them. Easily done, no redundant typing, very little pain.
Congrats, we've just made a framework. It's cheap, but it works.