Configuration Manipulation With PHP Config - Giving Birth (
Page 8 of 9 )
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
include("Config.php");
// initialize object
$c = new Config();
// create section
$mailSection =& new Config_Container("section", "mail");
// create variables/values $mailSection->createDirective("name",
"Bruce Banner"); $mailSection->createDirective("email",
"hulk@angry.green.guy"); $mailSection->createDirective("host",
"mail.apollo.domain");
// reassign root
$c->setRoot($mailSection);
// write configuration to file
$c->writeConfig("mail.conf", "INIFile");
?>
Here's the output:
[mail]
name=Bruce
Banner
email=hulk@angry.green.guy
host=mail.apollo.domain
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.