During a recent code review it was suggested that we should move from using an ini file to a JSON file for our Zend Framework application config file. The reason was to reduce duplication of data that can occur and instead move to a nicely nested file.
I wasn’t aware that JSON format config files were supported, but sure enough after a quick look at the Zend Framework documentation, there was the relevant class, Zend_Config_Json. It has only appeared in recent versions of the Zend Framework so that could be why I had missed it.
It’s easy to use in code, being almost a complete drop in for a the usual ini config.
$config = new Zend_Config_Json( './example_config.json', 'production' );
The first parameter is the location of the config file, the second is the section of the config file to use.
There is an optional third paramter that allows some addition configuration options to be specified such as changing the immutability of the config object once loaded, changing the behaviour of _extends
, and the ability to ignore constants. More details can be found in options section of the Zend_Config_Json manual.
Here’s a quick example. Firstly the JSON configuration file.
{ "production" : { "username" : "Robert Price", "beer" : [ "Harveys Sussex Best", "Spitfire", "Asahi" ] }, "testing" : { "_extends" : "production", "beer" : [ "Harveys Star Of Eastbourne", "Schwaben Brau - Das Helle", "Brauhaus J.Albrect - Dunkel" ] } }
OK, it’s a good real life example, but it has two sections, production and testing. Testing inherits from production by using the _extends parameter.
We can load and extract details using the following code.
$config = new Zend_Config_Json( './example_config.json', 'production' ); echo "Username is " . $config->username . "n"; echo "Favourite beers are...n"; foreach ($config->beer as $beer) { echo "* " . $beer . "n"; }
When you run this code you get the following results, assuming you saved the json config file from earlier as example_config.json…
Username is Robert Price Favourite beers are... * Harveys Sussex Best * Spitfire * Asahi
Now change the code so instead of production when we load the config file, we use testing. Run the code and you’ll get the following…
Username is Robert Price Favourite beers are... * Harveys Star Of Eastbourne * Schwaben Brau - Das Helle * Brauhaus J.Albrect - Dunkel
As you can see my username has been inherited from the production block, but the list of beers has changed. This is a very powerful feature that lets you change a small section of data between environments in real code without having to repeat yourself and reduces the risk introducing errors in duplicated config options.