Note to CodeIgniter nerds: please, no looping code in your views.
June 5, 2008
I was researching things ‘nerd’ on the Web today, and I found myself at the CodeIgniter website.
For those of you who may not know, CodeIgniter is an MVC PHP framework.
What is an MVC framework?
I won’t go into details here since we’ve covered MVC basics elsewhere. Let me just say though, that an MVC framework is a bunch of PHP code organized into a reusable structure/system designed to make building web applications easier.
MVC is short for:
The general idea is to keep code separated by it’s function.
Code used to talk to the database is contained in the ‘Model’ part of the code base. And the ‘view’ is the code (typically mostly HTML with some small bits of PHP mixed in) are basically the pages/views that people actually see … your basic web page.
… Don’t worry, I’m going somewhere with this.
I’m wondering about CodeIgniter’s decision to place PHP looping code in their views.
I had a few minutes to spare and so I watched their ‘Hello World’ video tutorial.
What caught my attention in this video was how the author was using PHP looping code in his ‘view’ template! This may not seem like a big deal to you, but consider these two points:
- The whole point of the ‘view’ in MVC is to keep as much PHP code out of the view templates as possible. For me, the main advantage of doing this is to keep your web designers from busting your PHP code.
- Looping code is the messiest PHP code you can possibly have in your pages … get it out of there!
… I remember back in 1996 (in my classic ASP days) where the biggest problem was trying to cleanly loop through recordsets in such a way so that web designers wouldn’t break the ASP code.
My own simple solution was to build the table rows in a page-widget helper object and then shoot back a simple string variable to the view. The web designer would then simply wrap the one line of PHP in a table tag:
<table> <?php echo $client_list; ?> </table>
This way the web designer is free to style the table anyway they want, and it’s way harder for them to break the page.
I haven’t really looked much at CodeIgniter, but if this introduction video is representative of how they do things … I’m wondering: why?