Better Models and Controllers in CodeIgniter
There’s no denying CodeIgniter is an excellent PHP framework, but its default implementations of the “M” and “C” parts of “MVC” leave a fair bit to be desired.
Want views loaded by convention? No such luck.
Want to include some partial content, like a sidebar, in your views? No can do. (Thanks to Simon for reminding me that partial content is possible after all) Basic CRUD functions in the models? Sorry, you’ll have to implement them yourself. Layouts? Afraid not.
But fear not, young Capuchin - Jamie Rumbelow‘s superb libraries give the models and controllers not so much a facelift as major surgery, and they look and feel all the better for it.
For example, you now have views loaded by convention based on the name. That is to say, if you hit the bar() function in the Foo controller, the system will automatically render the view views/foo/bar.php. This can be overridden if you want, too.
Also, models now have 16 basic functions built in, making it far quicker and easier to work with your data, as the model does all the heavy lifting for you - you just need to build up your query, and then decide what to do with the returned data.
Layouts and partial content also join the party, meaning that you can set up the majority of your HTML in a single file and only worry about the parts you’re actually rendering right now. You can have multiple layouts if you like, and choose which one to render each controller action in (e.g. you could have a separate admin layout for backend stuff) - you can also decide not to have a layout at all, which is essential if you want to use views to render the results of AJAX actions (like the comment form does on this very post, in fact - why not give it a try?).
So, if you’re using CodeIgniter and you haven’t yet taken advantage of these great additions, I would strongly recommend taking a look before you start your next project - you won’t regret it!
For more detailed instructions, and the links to download the files, visit Jamie Rumbelow’s blog.
Posted on Tuesday, 1st June 2010.
Sorry, feedback is now closed on this post, but please feel free to get in touch if you would like to talk about it!
Want to include some partial content, like a sidebar, in your views? No can do.
What about simply loading your sidebar from within your view?
Nested views are a piece of cake in CI…
Fair cop Simon - I had actually forgotten that was possible.
I think it’s because I wanted to do something similar in a previous project, but nested views didn’t suit for one reason or another. Can’t remember the exact reason if I’m honest. Have corrected the post now :)