Handle configuration in PHP with var_export()

Handling configuration file with PHP

During development i searched an easy way to handle configuration files, either via manual editing or via interface.
At first i was using parse_ini_file() but it becomes quickly clear that i was not made to handle complex data structure.

After some readings i finally end up using var_export() to handle my configuration files.
Note that var_export() also work with objects, but you need first to implement _set_state() which can be quickly painful, especially if your object link to other objects as everyone must have a _set_state() method, so in this example i will stay only with array.

The function var_export()

The goal of var_export() is to return a parsable string representation of a variable, in clear, it return valid PHP code.

It output immediately $expression in PHP code if $return is set to false, or return it as a string if $return is set to true.

What we want is to write our configuration array into a PHP file, so we will use it with $return at true, otherwise you can use ob_start() and ob_get_contents().

Here our configuration file example :

To include it and use it, we only have to require it, it will use PHP include_path to do so.

We can go even further by adding an environment variable (dev, prod, …) to it to handle and load the right configuration for the right place.

After load, we can implement all things that are needed to use and edit this configuration.
To save it as a PHP file, we must add a php open brace, the return instruction and a ; after the array for this instruction.
All the PHP code returned will be well formatted by var_export() to keep reading easy.

So I will stick with var_export() for the moment as it keep the configuration code clean and easy editable.

Leave a Reply