integrating phpdotenv ( .env ) files in CodeIgniter 3.0 using hooks

Screen Shot 2016-01-26 at 7.03.31 PM

So we all know one of the tenets of the 12 factor app is to store config in the environment. CodeIgniter allows production and development config and database files to be stored in separate directories. But they all reside inside the git repo and therefore not really safe for storing sensitive values like database connections params or auth codes.

In comes phpdotenv, a really clean way to achieve this. Laravel already implements this and it’s fairly easy to do the same in CodeIgniter as well. Here’s how :

Enable Composer

You can skip this step, if you already have Composer integrated to CI.

Composer makes PHP awesome. Although you can implement the above without composer but this method is way more elegant. The following config flag has to be turned on in your application/config/config.php file :

$config['composer_autoload'] = true;

Next create a composer.json file inside the application folder with the following contents :

After that you need to run “composer install” in that directory. If you don’t have composer installed, here is how to do it.

Add Hook

Now we create a pre_system hook to load phpdotenv. This is the most appropriate hook as it is called right after loading composer and before the controller. Here is what my application/config/hooks.php looks like :

And then enable hooks in application/config/config.php as it does not come enabled by default:
$config['composer_autoload'] = true;

A dirty way to do it would have been calling the same code in index.php file. But changing the core files of a framework is almost always a bad idea and makes upgrading/debugging very difficult.

Create a .env file

The hook code was configured to load the .env file from inside the applications folder. You can change that if you want.

And that’s it, you can keep separate .env on your production servers and on your dev server. The values can be accessed via either getenv() or $_ENV superglobal variables.

Nice. So that does it. Let me know if you have something to say in the comments.

Cheers!