Config helps you manipulate your configuration whether they are stored in XML files, PHP arrays or other kind of datasources. It supports these features:
The Config object acts as a container for other Config_Container objects. It doesn't do much but makes handling IO operations easier. It contains the root Config_Container object which in turn contains a child Config_Container object. Config_Container objects store references to their parent and have an array of children. This structure makes it easy to access the different containers and their contents.
A Config_Container object can be of different type:
When using the Config package, most of the work is done with Config_Container objects.
An example that will create a new Config_Container
<?php
// initialize a Config_Container object
require_once('Config.php');
$conf =& new Config_Container('section', 'conf');
$conf_DB =& $conf->createSection('DB');
$conf_DB->createDirective('type', 'mysql');
$conf_DB->createDirective('host', 'localhost');
$conf_DB->createDirective('user', 'root');
$conf_DB->createDirective('pass', 'root');
// set this container as our root container child in Config
$config = new Config();
$config->setRoot($conf);
// write the container to a php array
$config->writeConfig('/tmp/config_test.php', 'phparray',
array('name' => 'test'));
// print the content of our conf section to screen
echo $conf->toString('phparray', array('name' => 'test'));
?>
The above example illustrates how Config and Config_Container can interact. There are other ways. You could have for example first created the Config object and then used $config->getRoot() to add sections and directives to the returned object reference.
Reading configuration from an XML file
<?php
require_once 'Config.php';
$conf = new Config;
$root =& $conf->parseConfig('config.xml', 'XML');
if (PEAR::isError($root)) {
die('Error while reading configuration: ' . $root->getMessage());
}
$settings = $root->toArray();
printf('User settings: <a href="%s">%s %s</a>',
$settings['root']['conf']['www'],
$settings['root']['conf']['firstname'],
$settings['root']['conf']['lastname']
);
?>
In this example the XML file config.xml
looks like this:
<?xml version="1.0" encoding="UTF-8"?> <conf> <firstname>John</firstname> <lastname>Doe</lastname> <www>http://example.com/</www> </conf>
For more information, You can read API doc, sample of package, tests of package, and a great tutorial of DevShed about the Config package.