HomePHP Page 5 - Easy Application Configuration With patConfiguration
Version Control - 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.
Let's now consider a variant of the example on the previous page, this one printing the value of a single configuration variable:
<?
// include class
require("patConfiguration.php");
// create patConfiguration
object
$conf = new patConfiguration;
// set config file locations
$conf->setConfigDir("config");
//
read config file
$conf->parseConfigFile("config.xml");
// get configuration
values
print_r($conf->getConfigValue("application.version"));
?>
In this case, since the getConfigValue() method receives the path and name of
the configuration value to be retrieved, only that value is retrieved and printed.
Here's a more realistic example, this one using an XML configuration file containing MySQL database access parameters
<?
// include class
require("patConfiguration.php");
// create patConfiguration
object
$conf = new patConfiguration;
// set config file locations
$conf->setConfigDir("config");
//
read config file
$conf->parseConfigFile("config.xml");
// get and use configuration
values
$connection = mysql_connect(
$conf->getConfigValue("mysql.host"),
$conf->getConfigValue("mysql.user"),
$conf->getConfigValue("mysql.pass")
) or die ("Unable to connect!");
mysql_select_db(
$conf->getConfigValue("mysql.db")
)
or die ("Unable to select database!");
$query = "SELECT * FROM users";
$result
= mysql_query($query) or die ("Error in query: $query. " .
mysql_error());
mysql_close($connection);
?>