Simple config management for PHP


When doing complex applications it’s often nice to have some sort of system for handling settings. PHP has a nice function called parse_ini_file which can be used to create a basic but still usable setting file feature. A simple class which loads the configuration file and offers some methods to retrieve the values for a given key is all that’s needed. The example I’m providing is pretty basic, but it’s still very usable and can be added to almost any application.

First, we need to create a file to hold the settings. It’s ordinary plaintext and follows the INI format.

Here is a quick sample of some key / value pairs:

[general]
locale = no_NO
company.name = MyCompany

datasource.host = localhost
datasource.database = mydb
datasource.username = user
datasource.password = 1234

The class for accessing the file:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
class MyConfigClass{
  protected $config;
 
    public function __construct()
    {
      $this->config = parse_ini_file('../conf/myapp.ini');
 
    }
 
    public function getConfig($key = null)
    {
      if($key !== null)
      {
        if(isset($this->config[$key]))
        {
          return $this->config[$key];
        }
        else
        {
          throw new Exception("Unknown key '$key' in configuration");
        }
      }
      else
      {
        return $this->config;
      }
    }
 
    public function setConfig($config)
    {
 
      $this->config = $config;
    }
}
 
?>

Usage:

1
2
3
$configManager = new MyConfigClass();
 
$value = $configManager->getConfig['datasource.host'];

Now, when working on larger application one usually have a application like class, and that’s a nice place to put this code. When using Prado I usually place the config code in the TApplication class.

Technorati Tags:

Share and Enjoy:
  • Digg
  • del.icio.us
  • Facebook
  • Google
  • description
  • Live
  • Slashdot
  1. #1 by Thomas Koch - May 30th, 2008 at 10:18

    You may want to have a look at the Configuration component of eZComponents:

    http://www.ezcomponents.org/docs/tutorials/Configuration

    It does not only give an interface to configuration files in INI and PHP Array format, but also handles grouping of configuration settings and preserves comments in the configuration files.

  2. #2 by admin - May 30th, 2008 at 10:30

    Thomas: I’ve not tried it out yet, but it sure is interesting. I would expect to use this on larger scale applications, and the feature I posted in mid size perhaps? The EZ way seems a bit more complex at first.

  3. #3 by Ivo - May 30th, 2008 at 11:57

    It’s not a lot more complex, it just has a few more features. Maybe you’re going to need more features in the end, so might be a good idea to use the component.

    Other frameworks such as the Zend Framework have similar components you could use.

    Personally, I’ve never really seen the advantage of ini files over a plain php file.

  4. #4 by admin - May 30th, 2008 at 12:27

    Ivo: Thanks for commenting. I will definitely check it out. Not seen the Zend stuff yet, but will look into that as well. When it comes to ini files vs php files (at least in my case) we profit from using ini files. The reason for this is that .ini files are considered configuration files, while php files is code. Systech is happy when it comes to editing configurations, but not code ;)

  5. #5 by Jeremy Privett - May 30th, 2008 at 14:58

    Mostly as a note to the readers, as the writer probably knows this, but …

    For web applications, keep in mind that in most default setups ini files are returned to a browser in plaintext, meaning your database credentials can be exposed to anyone who happens upon your configuration file. Make sure you setup the appropriate rules to make sure access is denied to these ini files.

  6. #6 by Andrei - May 30th, 2008 at 16:41

    I highly suggest you add some sort of caching to this (preferably via APC). Otherwise you’ll end up hitting the disk and parsing config files (of which there may be multiple) on every request.

  7. #7 by Charlie - May 30th, 2008 at 18:50

    No fence, but I like the Zend_Config more :) Accessing config values as objects is a key to a great feeling.

    Example: $config->datasource->host

  8. #8 by Matthew Vines - May 30th, 2008 at 20:45

    In response to Jeremy,

    That is a great point, and something you should always try to be cognizant of as you set up your we projects. I find that one of the easiest ways to protect config files, whether, ini file format, or xml format, is to give them a .php extension. This way the server parses them as PHP (which ends up looking like a blank file to the browser). But your code doesn’t care what the extension is, as we are just working with a stream to a file, the extension is irrelevant. Only one way to go, but its a viable option for those who are not strong server administrators.

  9. #9 by Lux - May 30th, 2008 at 21:32

    We use ini files extensively for configuration info in our framework, but one thing to be mindful of if you’re storing sensitive info in there is to make sure it can’t be seen in the browser. You could do something in your config like this:

    Deny from all

    But we take an extra step I’d recommend taking as well:

    1) Make sure the files end in .php
    2) Add the following lines at the top and bottom:

    ;

    (Hopefully that renders okay :) Now if someone requests that in the browser, the site returns a blank screen with just “; ” on it. Hope that helps you out too.

  10. #10 by Lux - May 30th, 2008 at 21:33

    Looks like my examples didn’t make it through… Let’s try again:

    ; <?php /*

    ; */ ?>

  11. #11 by Michael Sharman - May 31st, 2008 at 00:53

    As a php noob…

    Why have the expense of instantiating an object each time for these static variable lookups, why not just include a config file?

    require_once “myConfig.inc.php”;

    Then just access the vars as normal? If overwriting is a concern you can always prefix with something like:

    $config_adminemail = “me@wherever.com”;

  12. #12 by Aaron Saray - June 2nd, 2008 at 17:27

    This configuration option is nice… but what about times when your configuration has to make a decision? For example, if I’m using the same code base over multiple partner websites, but the name is different, I need to make a choice on what name to display as the global one.

    INI files would allow you to have either 1) multiple INI files - kinda code duplication or 2) have them outside of the code base - which may make them naked to versioning software.

    I’ve found that I end up using a class with a static ‘get’ method - that creates a new instance of itself in singleton pattern - which performs all of the logic calculations.

    Keep up writing!
    -aaron

(will not be published)