Easy Application Configuration With patConfiguration - Version Control
(Page 5 of 11 )
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
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<path name="mysql">
<configValue
name="host"
type="string">localhost</configValue>
<configValue name="user"
type="string">joe</configValue>
<configValue name="pass"
type="string">secret</configValue>
<configValue
name="db" type="string">db456</configValue>
</path>
</configuration>
to open up and use a database connection.
<?
// 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);
?>
Next: The Write Stuff >>
More PHP Articles
More By Vikram Vaswani, (c) Melonfire