Developing software in the Real World

Using Zend\Config with a Slim app

Sometimes you need more configuration flexibility for your application than a single array. In these situations, I use the Zend\Config component which I install via composer:

This will install the Zend\Config component, along with its dependency Zend\Stdlib.

Let’s look at a couple of common situations.

Multiple files

It can be useful to to split your settings files out for administrative or environment-specific reasons. To set up within a Slim application, you do something like this.

The key class that we’re interesting is in Zend\Config‘s Factory which takes a list of config files, loads each one and merges into a single array. If all your configuration files live in the same directory, then you can quite easily use a glob pattern:

This pattern will load all files starting with global before those starting with local. Hence, for the files: local.php, global.php, local.foo.php and global.foo.php, the order will be:

  1. global.foo.php
  2. global.php
  3. local.foo.php
  4. local.php

So, the local files will override the global ones. Each settings file needs to simply return an array.

Other formats

You may want to use a format other than PHP arrays. Zend\Config supports Ini, XML, JSON, Yaml and JavaProperties in addition to PHP arrays. You can mix and match too. Note that you’ll need Zend\ServiceManager, so install it using:

If you use JSON, you also need:

For example, given:

global.ini:

local.json:

Then you can load these configuration files using:

This will load files in this order: global*.json, global*.ini, local*.json and then local*.ini. Again, you end up with a single array in $settings, the var_dump shows that it contains:

To sum up

That’s all there is to it really. Zend\Config‘s Factory in conjunction with glob is a very flexible solution that allows you to put in place the exact configuration strategy that you want to, using the configuration format that you are most comfortable with.

2 thoughts on “Using Zend\Config with a Slim app

  1. Not sure what is the point of using this extra libray when you can simply return a config array from a file for all your environments something like:

    return [
    'local' => ['foo', 'bar'],
    'dev' => ['foo', 'bar'],
    'live' => ['foo', 'bar'],
    ]

  2. Clean and simple solution to integrate components with Slim framework.
    Great article, as usual.

    It's been a while since I started to work in a project where we have been integrating plenty of ZF2 components with Slim, and your last articles have been very useful.
    We've also integrated symfony components and "the PHP league" libraries, as well as opther third party libraries. Everything is easier with composer.

Thoughts? Leave a reply

Your email address will not be published. Required fields are marked *