HomePHP Page 6 - Easy Application Configuration With patConfiguration
The Write Stuff - PHP
Tired of handcrafting configuration file manipulation tools for your Web application? Save yourself some time with patConfiguration, a PHP class designed to assist developers with reading, writing and maintaining application configuration files.
So that takes care of reading configuration files - now how about writing them?
In the patConfiguration universe, creating a configuration file is a two-step process: first add one or more entries (variable-value pairs) to the configuration stack, and then write the stack to a file. patConfiguration comes with a setConfigValue() method that takes care of the first step, and a writeConfigFile() method that takes care of the second one. Consider the following example, which demonstrates:
<?
// include class
require("patConfiguration.php");
// create patConfiguration
object
$conf = new patConfiguration;
// set config file locations
$conf->setConfigDir("config");
//
set config values
$conf->setConfigValue("screen.width", 500);
$conf->setConfigValue("screen.height",
650);
// write file
$conf->writeConfigFile("config.xml", "xml");
?>
The setConfigValue() method accepts two primary parameters - variable name and corresponding value - and a third optional parameter, which is the datatype of the variable being set (if this third value is omitted, patConfiguration will automatically determine the variable type). Valid type values include "string", "integer", "boolean", "float" and "array" - I'll be discussing these again a little further down.
Once the variable-value pairs have been created, the writeConfigFile() method is called to actually write the configuration data to a file. In addition to the file name, patConfiguration also allows you to specify the file format - "xml" or "php" - together with a couple of miscellaneous options that adjust the behaviour of the writeConfigFile() method.
You can set multiple configuration values at a time via the setConfigValues() method, which accepts an array of variable-value pairs
<?
// include class
require("patConfiguration.php");
// create patConfiguration
object
$conf = new patConfiguration;
// set config file locations
$conf->setConfigDir("config");
//
create array of configuration values
$config = array(
"screen.height" => 650,
"screen.width"
=> 500
);
// add to configuration table
$conf->setConfigValues($config);
//
write file
$conf->writeConfigFile("a.xml", "xml");
?>
and clear a value using the clearConfigValue() method.
<?
// include class
require("patConfiguration.php");
// create patConfiguration
object
$conf = new patConfiguration;
// set and display value
$conf->setConfigValue("name",
"Superman");
echo $conf->getConfigValue("name");
// clear and check to see if
value exists
$conf->clearConfigValue("name"); echo $conf->getConfigValue("name");
?>
Note that if no path is provided to clearConfigValue(), the entire configuration table is cleared.