After hanging around on StackOverflow.com for so long, I’ve started seeing bad programming patterns in the way new posters go about creating code, specifically using CodeIgniter, an MVC Framework. The code they write almost always shows a general lack of understanding of MVC design.

A typical ‘bad programmer’ will create a controller, which would just call a view:

function index()
{
	$this->load->view('process_something_page');
}

and then their view would be jam packed with business logic, database queries, and very much a glob of code that defeats the whole purpose of utilizing an MVC framework.

WAKE UP!

  • Keep your Controllers skinny, and free of business logic
  • Stick your business logic, into your MODELS
  • Your VIEW should output results/output generated from your MODELS
  • As a programmer, do it RIGHT from the START, don’t say “I’ll fix it later”, later never comes!
  • If you don’t know where something should go, ask (StackOverflow is a great place to ask, make sure to properly define your question tho)

I’ve created a brief and somewhat comical view of what you should do to keep your MVC pattern clean. Just remember, don’t put it all in the VIEW, even if you are just doing a ‘test’, be smart about where you put things.

Controller

  • Control the flow of logic, when business logic is needed, utilize a model, once output is gathered, call a view
  • Don’t add business logic here that results in a if/else check and logic, leave that for the model, return the result to the controller
  • Keep your controller skinny, if you are calculating something, it shouldn’t be in there.

Model

  • Where your business logic goes, if you have conditions that need to be met, and data pulled on those conditions, let the model handle that lifting.
  • Most people associate a model with a database interaction, while true, that’s not all its used for. Keep that in mind.
  • Don’t format your data output for HTML, or anything specific, a models data object should be generic. Styling data should be done in the view.

View

  • Free of logic, should not have any validation, error checking, or database queries.
  • Focus on displaying data provided by the model, style the output here.
  • A view should be flexible enough that output works for command line output, web app output, or mobile output without much work.

You might ask yourself, “Why does it matter that I use proper MVC patterns?”, and in truth, it doesn’t matter unless you work in a group, or if you are the type of person that wants to maintain code in the future. As always, if I misrepresented something, or am flat out wrong, let me know. Post your comments below.



Leave a Comment