HomePHP Page 8 - Configuration Manipulation With PHP Config
Giving Birth - PHP
Tired of writing (and rewriting) code to manage your application's configuration variables? Take a look at the PEAR Config class, a PHP toolkit designed specifically for manipulating configuration files and the data within them. This article demonstrates using the Config class to read and write configuration files in XML, PHP and INI formats, and use built-in methods to easily build Web-based application configuration modules.
The sharp-eyed amongst you would have noticed that the previous example made one important assumption: that the configuration file existed in the first place. If it didn't, the code on the previous page would return an error - not something you want happening the first time your application is installed.
With this in mind, the Config class also comes with a number of methods that allow you to create a complete configuration file from scratch. Consider the following example, which demonstrates:
// include file
// initialize object
$c = new Config();
// create section
$mailSection =& new Config_Container("section", "mail");
In this case, an object of the Config_Container class is initialized as a section named "mail", and a reference is obtained to it. This reference is used to build the rest of the configuration tree via the createDirective() methods. Once the tree is complete, a call to setRoot() takes care of resetting the root reference to the newly-created section, and a call to writeConfig() writes the entire tree to the named file.
In addition to the createDirective() method, the class also includes createSection(), createComment() and createBlank() methods, designed specifically to create sections, comments and blank lines respectively. Take a look at the manual pages for more on these methods, together with usage examples.