May 13 2009

Building Applications using CodeIgniter (Part 4) – Code Templates

by Chris

Last July I wrote a post entitled “What does your code say about you?” In that post I discuss the importance of writing clean well formatted code. It’s vitally important, even if you are the only programmer working on a project, that you document and format your code because you may be the only programmer now but who knows about 6 months or a year from now. Plus, as a programmer, the code you write is a direct reflection on you as a professional.

So far in this series I’ve discussed my typical application structure, configuration and helper files when developing apps using CodeIgniter (CI). In this final post I’ll review creating code templates for quick consistent development.

There is nothing really functional/technical about code templates. Templates are a set of simple files that have the basic document structure for the specified file (controller, model, library, etc.) that you use as a common starting point when creating any new file for your app. Your template should contain common elements to all files like the header comment block, class declaration, constructor, etc. There is no need to come up with your own standard when creating your templates because CI has a very nice style guide you should follow.

CI Style Guide

A few versions ago, CI added a page to their users guide entitled PHP Style Guide. In this section they do a great job at outlining the proper format when declaring variables, writing comments, naming files, etc. This is a great place to start when creating your templates. If you don’t already, you should think about getting in the habit of following these standards (even if you aren’t programming with CI) because they will help keep your code clean and consistent.

Template Files

Before I start coding my app I typically create a template file and place it in the controller and model folders. The templates are different of course, but they both create a nice starting point whenever I need to create a new file. It’s important to note that you don’t necessarily have to create physical template files to accomplish clean and well formatted code. Some tools like Coda and TextMate give you the ability to save bits of text and reuse them in your files. So you could create your header comment block and save it in your editor and just call upon that whenever you create a new file. Doesn’t really matter how you do it, it just matters that you do.

That’s a Wrap

OK… lecture over. That does it for the building applications using CodeIgniter post series. If interested, you can download a copy of the final CI install that we’ve created over the last 4 posts with helpers, code templates and all.

I hope by sheding some light on my process and explaining how I do things you came up with some ideas on how you can improve your own CI apps. As always, feel free to leave any questions or feedback as a comment below.