Big picture thoughts on software and other topics

February 18, 2008

MVC or MVA? Or, What Do Controllers *Do* Anyway?

by Brian Donahue

I've been looking at and working with Model-View-ControllerBroken Link: http://en.wikipedia.org/wiki/Model-view-controller frameworks off and on for a couple years now, from Rails to Monorail to ASP.NET MVC.  I've been taught that the Controller is a first class citizen, responsible for application flow (at least handling request/responses) and rendering views, etc.   The Controller gets its name in lights, right next to the Model, and the View.

But what does the controller really do?  By far the most popular pattern is for controllers and their actions to map to URLs such that /people/list maps to a PeopleController's List() method. So, are controller's just "Action aggregators?"  Are they basically namespaces for URL pattern matching (i.e. /[controller]/[action])?

While this was probably not the original intention for the pattern, in practice it seems to be the case.  Further spark for this line of thought for me was hearing JP BoodhooBroken Link: http://jpboodhoo.com/ describe how he implemented a simple MVC framework that was basically a Command PatternBroken Link: http://en.wikipedia.org/wiki/Command_pattern.  JP's implementation matched requests (url + payload parameters) to a command, which handled the request and, if necessary, to a view that would render the results - bypassing the controller completely.  Monorail's Dynamic ActionsBroken Link: http://www.castleproject.org/monorail/documentation/v1rc2/advanced/dynactions.html approach this pattern by creating Action objects, that can be indexed to an action name in a controller:

public class MyController : Controller
{
public MyController
{
DynamicActions["index"] = new IndexDynamicAction();
}
}
The Controller/Action paradigm also brings some baggage when it comes to actions that are similar or shared across several controllers.  Controller inheritance can get real ugly real fast.  Hammet and others have sungBroken Link: http://hammett.castleproject.org/?p=73 the praisesBroken Link: http://adamesterline.com/2007/08/27/monorail-dynamic-actions-the-better-way-to-implement-actions/ of Dynamic Actions to alleviate some of these issues, but to me, it begs the question, "why not just throw away controllers altogether?"

I wonder why we don't just focus on the Routing infrastructure to map requests directly to Actions and Views, which are the real "players" in the system.  This would allow for easy Action reuse, aggregation, inheritance, etc - all the benefits of the Command Pattern.

When I get a chance to get back to some real coding with any of the MVC frameworks I've used, I hope to experiment with this and see what I can come up with. 

In the meantime, I'm curious to hear other people's ideas on the value (or lack thereof) of the Controller in MVC?