Ok – I’ve been looking at the MVC design pattern, and need to clarify the way it’s supposed to work. I’ve done lots of reading, but as I’m new to DP’s it’s all fuzzy to me.
In an MVC, the model will handle my database work for me. That seems to be the simplest part.
The controller will handle the processing – dealing with forms, getting data from the model etc.
The problem for me is the view. Let’s say I was looping through a resultset from a database query. When looping through the results, I might need to perform an if/else. Now, typically it seems that would be done within the View – but that seems counter intuitive to me. As soon as you need to start performing checks like that in the View, it seems the view is no longer just for presentation, but for processing logic just like the controller does. I also imagine that this could make for messy code within the View, but that’s a different matter.
So, is the View an ok place to put small bit’s of operation on the code, or is there somewhere else I should be putting that code? I know I could create a class method in a library somewhere else, but that seems like it would over complicate things un-needlessly.
I’ve tagged this with PHP as it’s the primary language I work with.
ASP .NET MVC developer here, but I’m not sure that it matters given the nature of the question.
I try to think of a view as everything I need to render a particular operation. This will include stuff that is tied to specific business concepts, but also, will cover things like pagination and other concepts that aren’t domain-specific problems, but still require some representation on the page.
Now, in terms of code operations, in some senses there isn’t a lot you can do. You may have a part of your page that is dependent on, say, a collection being populated and having things in it. I have no real problem sticking in simple conditional constructs to handle things like this. It is code, but you could argue that its not important code. We aren’t performing work per se, merely suppressing the display of certain elements based on the internal state of the view.
I’d argue that would apply to a lot of simple conditional display logic.
However, if you find that you are performing stuff that is more complex than that, it’s probably best to change the model to give the view less work to do. e.g. if you’re performing some nasty chained ternary in view-side markup, you may wish to consider encapsulating that logic in the construction of the model, instead of leaving it for the view to sort out.
So in conclusion, while simple on/off presentational constructs are generally okay (if a little messy) in views, consider creating extra properties etc on your model if you find your view code becoming inordinately complex or unmaintainable.