MVC and Codeigniter


Codeigniter is a damn good PHP framework. Very quick, and very easy. Great.

The problem though, was getting into it. Examples are typically a tiny blog application with minimal functionality – ok it gets you started, but when it comes to following the MVC structure, one problem very quickly arose - repetitive code.

Lets say you have a site with a more reasonable number of pages. Sticking to the pattern, controller functions do not call other controller functions – just models, and passing results into views (simplified explanation). Now, this quickly lead to masses of repeated code to gather data for the page header, left, and right columns.

Of course they can go into a library, but even then there are contrasting opinions – libraries can make a large task much easier (and of course, stripping out repetitive code), but when it comes to the task which the Controller should handle, then comes the dilemma of an “ugly pattern which breaks the rules” or the same code pasted again and again into various controller functions just to build the common parts.

After trying to be strict with the pattern, the result was a huge mess of similar code everywhere. Not acceptable.

Phil Sturgeon (one of the legends behind the framework) posted on his blog about extending the Core Controller class to handle common tasks such as whether the user can view the page (with admin permissions). I took this further, and implemented another layer – a “layout” controller.

This controller handles the common views – the left column, right column, the header, and footer. Each controller method calls just one function, which in turn calls the left, right, header, footer functions to construct the page, then the controller function itself handles the logic dedicated to the actual page in question.

This approach has shaved off 70% of the code for the controllers. None of the controller code is repeated, so when it does come to making a “quick change”, it is done in one place, not potentially ten or more.

At this point I don’t care if it breaks some strict rule of patterns – it makes the job much more efficient for the development team, and the code is still very predictable. I would rather spend the time creating new functionality than carefully duplicating the same fixes into the same copies of code throughout the controllers – a framework is supposed to handle the typical support code to let the coder get straight into productive development work. Codeigniter does a very good job of this.

Rest assured though, I do not blame Codeigniter for this – nor anyone in particular. It was my dilemma of trying to be strict and follow ‘standards’/rules, vs doing The Right Thing. I fail to see how drastically simplifying the code and improving efficiency dramatically is a bad thing.

  1. No comments yet.
(will not be published)