HomePHP Page 9 - Easy Application Configuration With patConfiguration
When Time Is Money, Recycle! - 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.
Here's another example, this one demonstrating how patConfiguration can be used in the context of a script accepting user input for application configuration. This script is divided into two parts: a form which displays the current configuration (if available) and allows the user to edit it, and a form processor, which accepts the new configuration and saves it to a file.
In addition to patConfiguration, this script also uses the patTemplate engine for the actual interface generation - you can read more about patTemplate at http://www.devshed.com/Server_Side/PHP/patTemplate/
<?
// include classes
require("patConfiguration.php");
require("patTemplate.php");
//
create patConfiguration object
$conf = new patConfiguration;
// set config file
locations
$conf->setConfigDir("config");
// create patTemplate object
$template
= new patTemplate;
// set template location
$template->setBasedir("templates");
//
add templates to the template engine
$template->readTemplatesFromFile("configuration.tmpl");
//
form not yet submitted
if (!$_POST["submit"])
{
// check to see if config file
exists
if (file_exists("config/config.xml"))
{
// parse it and display configuration
values
$conf->parseConfigFile("config.xml");
$template->AddVar("form", "DB_HOST",
$conf->getConfigValue("db.host"));
$template->AddVar("form",
"DB_USER",
$conf->getConfigValue("db.user"));
$template->AddVar("form", "DB_PASS",
$conf->getConfigValue("db.pass"));
}
//
parse and display the template
$template->displayParsedTemplate("form");
}
else
{
//
accept the submitted values
// and write them to a configuration file
$conf->setConfigValue("db.host",
$_POST['db_host']);
$conf->setConfigValue("db.user", $_POST['db_user']);
$conf->setConfigValue("db.pass",
$_POST['db_pass']);
$conf->writeConfigFile("config.xml", "xml", array("mode"
=>
"pretty"));
}
?>
In this case, patConfiguration is used to read the application's database configuration
from a file via the parseConfigFile() method and display the variable-value pairs contained within that file in an editable HTML form. The user may then modify these values and submit the form; patConfiguration will accept the new values and write them back to the configuration file via writeConfigFile().
This kind of application configuration is pretty common to most Web-based tools - and patConfiguration lets you build an interface around it quickly and efficiently, with maximum code reuse and minimal time wastage.