• 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
MVC best practices, to display the models

The scenario is : I'm currently implementing CRUD (+display) in my ORM class. To enable this : I have the "base" class dealing only with database stuff (fectching, updating,...) and I'm coding a subclass of this base class for CRUD stuff. Perhaps because I'm a lazy guy, and perhaps because it's simplest, I'm confronted to this dilemna : if I respect the MVC rules, I have to duplicate the processing : once for my model to output itself as an array, and once for the controller or view, that parses the array and sends back HTML.

Because it's duplicate processing, and because it duplicates code too, I came to a solution I find elegant, that is a function that, without argument, returns the array, and with an argument (more or less a hash of templates) directly returns HTML.

But MVC design doesn't strictly allow this, and I'm wondering if it's only bad in theory (in this case I don't care), or if that could lead me to problems when developing my "business" classes, that will extend the "orm crud" class.

You're right - you're facing a dilemma because you're attempting to have the model 'output itself'. Get rid of that thought pattern and the fog will lift... Models aren't supposed to output themselves.

You correctly identified two main schools of thought. And the Model is neutral in both. It provides business data, plain and simple - regardless whether queried by a controller or a view-script.

Which method to use for display may depend a lot on what else needs to be done. Perhaps the single model call is not enough to supply all the data a view might need and you need to query additional models to retrieve related data. Once that happens, you start dealing with error logic, because there is no guarantee that the model will provide data that let's you go further in your script and you may want to output a warning or something. If you're already in the view - while possible - it's a bit late to switch gears and ultimately you could end up with a jumble of checks in all kinds of places.

That's why I tend to stick with approach #1.


Thanks for that clarification. If I get rid of the model attempt to output itself, then the best is to create a library that takes model and templates and returns model output, for example :

// somewhere in controller
$tpl = array();
$tpl['main_content'] = $this->crudclass->output_html_edit($ormobject,$view_files);
// error checking, etc...

// output

Digg   Delicious   Reddit   Facebook   Twitter   StumbleUpon  

  Theme © 2014 iAndrew  
Powered By MyBB, © 2002-2021 MyBB Group.