Setting up Multiple Environments in CodeIgniter

With CodeIgniter 2 comes built-in environment handling for your PHP app. For those of you deploying to the cloud, making your application environment-aware is a must. I found no good online guide for setting this up in CodeIgniter 2's, so in this post I'll show you how to take this feature from out-of-the-box to deployable.

Environments are useful when your app has to run in two contexts — your computer and a web server — or more, in the case of teams working on the same app - some of whom may be working on Windows and others on Linux or OS X. CodeIgniter 2 specifies in its index.php:

You can load different configurations depending on your current environment. Setting the environment also influences things like logging and error reporting.

Set up index.php

CodeIgniter is set to default to development mode, but there's no way of changing it without writing your own code. Let's first modify index.php so that it senses whether it's being run in your local environment (by testing the hostname, which in my case is "sonar.local").

The rest of index.php sets the error handling based on what environment we set above, so we need not modify it.

Create Production and Development folders in your Config directory

The location that needs the most attention when working with environments is your application/config folder, where you need to specify different databases and global variables for each environment. Fortunately, CodeIgniter 2 has a feature built in that will sniff out folders in your config directory that share the name of your environments (e.g. application/config/development/config.php), and use the files in that folder to config itself. So with that in mind, here's my config directory structure.

/application/config/

  • autoload.php
  • constants.php
  • doctypes.php
  • foreign_chars.php
  • hooks.php
  • migrations.php
  • mimes.php
  • profiler.php
  • routes.php
  • smileys.php
  • user_agents.php

/application/config/development/

  • config.php
  • database.php

/application/config/production/

  • config.php
  • database.php

Any files in /application/config/ that you need to customize from environment to environment should be duplicated and put in their respective environment folders.

That's it for now, if you have any questions, you can find my contact info on my about page.