HomePHP Page 5 - Configuration Manipulation With PHP Config
Array Of Hope - PHP
Tired of writing (and rewriting) code to manage your application's configuration variables? Take a look at the PEAR Config class, a PHP toolkit designed specifically for manipulating configuration files and the data within them. This article demonstrates using the Config class to read and write configuration files in XML, PHP and INI formats, and use built-in methods to easily build Web-based application configuration modules.
So that takes care of writing configuration data to a file - now, how about reading it in?
Reading configuration data in from a file is accomplished via the parseConfig() method discussed previously - the only difference is that where earlier you handed the method a PHP data structure, here you pass it a file name (together with the second argument indicating the type of file). Once the data has been read in, a number of other methods become available to access the various key-value pairs.
Consider the following sample XML configuration file,
What happens here is pretty simple - the parseConfig() method reads the XML configuration file, parses it and places it into a private member of the object, and simultaneously exposes a root object that can be used to interact with the configuration variables. This root object comes with a toArray() method, which can be used to convert the XML configuration data into a native PHP associative array (there's also a toString() method that can be used to convert the data structure into a neatly-formatted string for display).
If you want the value of a specific configuration variable (rather than the whole caboodle), it is simple to obtain it from the associative array created via toArray(),by drilling down to the appropriate key. Consider the following revision of the example above, which illustrates by retrieving the various configuration values and using them to connect to a MySQL database:
<?php
// include class
include("Config.php");
// instantiate object
$c = new Config();
// read configuration data and get reference to root
$root =& $c->parseConfig("mysql.conf.xml", "XML");
// convert data into PHP array
$config = $root->toArray();
// open connection to database
$connection = mysql_connect($host, $user, $pass) or die ("Unable to connect!");
mysql_select_db($db) or die ("Unable to select database!");
// execute query
$query = "INSERT INTO stocks (symbol, price) VALUES ('HYYJ', 198.78)";
$result = mysql_query($query) or die ("Error in query: $query. " .
mysql_error());
// close database connection
mysql_close($connection);
?>
OOP purists will be pleased to hear that there's also a more elegant method to retrieve data from a configuration file - more on that on the next page.