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.

[tags]PHP[/tags]