What are the best practices for CodeIgniter?
One example would be to not include the ./system/application/config.php
and ./system/application/database.php
in the source code control. Better yet, rename config.php
to something like config.default.php
containing the default configurations that will more likely be similar across environments (dev/production) so it would be easier for others accessing the files to modify and rename to their respective names.
Prefix or suffix your controllers and models with Controller_ and Model_ respectively (like in Kohana). Often there will be times when a controller and a model might have same names.
There are many community developed best practices in CodeIgniter simple because it is so loose. For example, you can have your own naming conventions for controllers and models. I use the singular word for the front end controller, the plural word for my backend controller and then the singular word + model for my model names. Here's an example.
Front end: page.php Back end: pages.php Model: pagemodel.php
You can also move the 'application' directory out of the 'system' directory. This helps keep a clear separation between the framework core and your own application. It also makes sharing one CI install between multiple projects easy and also makes updating CodeIgniter very simple as well.
These are just a few but there are sites out there that will help you learn CodeIgniter. My own website programmersvoice.com has been described as a good resource.
Do not end your controller and model classes with ?>
to close the php tag. Just leave it open.
Make sure there are no whitespaces before the opening <?php
tag, would cause some HTTP header issues.
My tip would be to keep everything as abstract as possible.
Don't put all of your business logic in your controllers, because if you find one day you need to use the same logic in different controllers or methods, you'll be stumped.
Put as much business logic in your models/libraries as you can. Some people only generally keep database abstraction layer in their models, some people put everything in - it's up to you. The best thing to do is find an approach you like and stick with it. It won't come to you instantly, give it chance. Good programmers are made from experience and doing things wrong.
In general, keep your models FAT, controllers SKINNY, and views DUMB.
This means like I say, most logic in your models, only very fine abstraction between model <-> view in your controller, and ONLY presentation logic in your view.
If you have to do any complex logic in your views, you have structured your code incorrectly.
Hope that helps.