[developer shed network] server side - php - configuration manipulation with php config

Upload: eminemb

Post on 04-Jun-2018

229 views

Category:

Documents


0 download

TRANSCRIPT

  • 8/13/2019 [Developer Shed Network] Server Side - PHP - Configuration Manipulation With PHP Config

    1/29

    Configuration Manipulation With PHP Config

  • 8/13/2019 [Developer Shed Network] Server Side - PHP - Configuration Manipulation With PHP Config

    2/29

    By icarus2003-09-04

    Printed from DevShed.comURL: http://www.devshed.com/Server_Side/PHP/PHP_Config/ 

    Space And TimeOne of the most important tasks when building software applications is gaining a clear understanding of whichparts of the application can be configured by the user, and which parts cannot. For example, if you're building a

    generic tool to administer databases, you would obviously want the DBA to be able to configure the application fordifferent databases by inputting the database names and access parameters for each. However, you might notwant to give the DBA control over other aspects of the application - for example, the protocol version used forcommunication with the RDBMS, or the method of RDBMS file access - as these would be internal to your codeand also perhaps too complex for user-level configuration.

    Although making such decisions might appear trivial and largely a matter of common sense, they are no smalltask, especially for complex applications - deciding which aspects of your software are configurable by the user issomething that requires a thorough understanding of both the software's goals and the end-user requirements it isbuilt to address, and it can take even experienced developers a fair amount of soul-searching to get it right.

    Once the configuration variables within your application have been identified, it is traditional to separate them fromthe standard variable namespace and place them in a separate area, such that they may be manipulated

    independently. Most often, these variables are placed in one or more configuration files, and a user interface isbuilt to interact with these variables, to read them, and to modify them as required.

    That's where this article comes in. Over the next few pages, I'm going to introduce you to a toolkit designedspecifically for manipulating configuration files, thereby reducing the number of lines of code needed to read andmodify application variables. This toolkit is written in PHP, one of my favourite languages, and implemented as aclass, suitable for use in any PHP-based application and accessible via standard OO techniques. Flip the page,and let me introduce you to Config.

    Plug And PlayThe Config class is brought to you by PEAR, the PHP Extension and Application Repository (http://pear.php.net).

    In case you didn't know, PEAR is an online repository of free PHP software, including classes and modules foreverything from data archiving to XML parsing. If you need a widget to perform a specific task, and you don't feellike writing it yourself, take a look at PEAR - chances are good that someone's already done the hard work for you.

    In case your PEAR distribution didn't include Config, or if you chose not to install the PEAR component, you canget yourself a copy from the official PEAR Web site, at http://pear.php.net/ - simply unzip the distribution archiveinto your PEAR directory and you're ready to roll!

    Very simply, Config provides application developers with a set of APIs that ease the task of reading, writing andmaintaining application configuration files. As a tool designed to assist in the manipulation of data, it is capable ofproducing configuration files in a variety of formats, including Windows INI, XML and PHP formats.

    If you're in the business of building Web applications, and if those applications require some amount ofconfiguration to get up and running, you're going to find Config invaluable to your development cycle. Written as aPHP class, Config can easily be integrated into any PHP-based Web application, and can substantially reduce theamount of time you spend manipulating application configuration files and data. You'll find it functional, powerfuland (if you're the kind who likes fiddling) easily extensible, and it'll soon be a standard component of everyapplication you write.

    There's only one problem with Config - it could do with better documentation. The documentation available on thePEAR Web site is a little too terse for novices, and can throw up more questions than answers if you're coming atit cold. Hopefully, though, the next few pages will help resolve that problem, by illustrating how powerful the classreally is with some simple examples.

    Your Friendly Neighbourhood HulkNow that the hard sell is over and you're (hopefully) all set up with Config, let's take a simple example to see howit works.

    Let's assume that I have a PHP associative array containing a series of configuration variables, as in the followingsnippet:

  • 8/13/2019 [Developer Shed Network] Server Side - PHP - Configuration Manipulation With PHP Config

    3/29

    Normally, these configuration values would arrive via user input, perhaps via a form, perhaps through command-

    line entry. For simplicity and ease of understanding, however, I' m hard-wiring them for the moment; once you' veunderstood the basics, a subsequent example will demonstrate how they can be extracted from a form.

    The task at hand now consists of storing them permanently, by saving them to a configuration file. With the Configclass, this is a snap - consider the following script, which demonstrates:

  • 8/13/2019 [Developer Shed Network] Server Side - PHP - Configuration Manipulation With PHP Config

    4/29

    Let' s dissect this a little to see how it works.

    1. The first step is, obviously, to include all the relevant files for the class to work.

    Once that' s done, I can safely create an object of the Config class.

    This object instance will serve as the primary access point to the data in the application configuration file(s),

  • 8/13/2019 [Developer Shed Network] Server Side - PHP - Configuration Manipulation With PHP Config

    5/29

    This object instance will serve as the primary access point to the data in the application configuration file(s),allowing me to do all kinds of nifty things with it.

    2. Next, the object' s parseConfig() method is used to read the configuration data into the object.

    An interesting point to note is the second argument to parseConfig(); this is a predefined type that tells the Configobject the format or structure in which the configuration variables are stored, thereby simplifying the task ofextracting those variables and restructuring them as per the object' s internal requirements. The Config objectdefines a number of such formats, covering most of the major types of configuration files - here' s a list of the

    important ones (there are a couple more, take a look at the manual for more details):

    1. "GenericConf" - a generic configuration file consisting of colon-delimited variable-value pairs, such as thefollowing:

    2. "IniFile" - a Windows-style initialization (INI) file, such as thefollowing:

    3. "PHPArray" - a PHP associative array, such as the following:

  • 8/13/2019 [Developer Shed Network] Server Side - PHP - Configuration Manipulation With PHP Config

    6/29

    4. "XML" - an XML file, such as the following:

    The second argument passed to parseConfig() thus tells the Config object how the configuration variables arestored, thereby activating the rulesets needed to read and manipulate them.

    4. Once the configuration data has been read into the object via parseConfig(), you can use it for whateverpurpose you wish - to retrieve an individual value (or set of values) from it, to modify values, or to write the data toa file. Coincidentally, the script above picks door number three, writing the configuration data to a file named

    "mail.conf" in the current directory via the writeConfig() method.

    Note that here too, the second argument to writeConfig() is a type identifier - this tells Config what format the datashould be written in. As you will see shortly, altering this parameter significantly affects the format of theconfiguration file.

    When you run this script via your Web browser, the configuration data in the PHP array $mailConfig will be writtento a configuration file named "mail.conf", as noted previously. If you look into this file, you should see somethinglike this:

  • 8/13/2019 [Developer Shed Network] Server Side - PHP - Configuration Manipulation With PHP Config

    7/29

    $email = ' [email protected]' ; $host = ' mail.apollo.domain' ; ?> 

    If you don' t like this, the writeConfig() method also offers you a further degree of customization when dealing withthe PHPArray type - you can specify that the variable-value pairs be structured as an associative array of key-value pairs (rather than regular variables, as above) by adding an optional third argument to writeConfig(). Here' show:

  • 8/13/2019 [Developer Shed Network] Server Side - PHP - Configuration Manipulation With PHP Config

    8/29

    In this case, the data written to "mail.conf" will be structured as an associative array with the name $mailSettings.Here' s what the file would look like:

    Different Strokes

    I noted, on the previous page, that altering the second argument towriteConfig() significantly affects the format of the configuration file. Let' s look at that a little more closely, by tryingout the different variants. Consider the following rewrite of the previous example, which writes the configurationdata as a generic configuration file instead of a PHP structure:

  • 8/13/2019 [Developer Shed Network] Server Side - PHP - Configuration Manipulation With PHP Config

    9/29

    Here' s what it looks like:

    name:Bruce Banner email:[email protected] host:mail.apollo.domain 

    As with the PHPArray type, you can customize the output format by specifying the characters to be used forcomments, delimiters and line endings. So, for example, if you wanted the variable-value pairs separated bycommas, you could use this script,

  • 8/13/2019 [Developer Shed Network] Server Side - PHP - Configuration Manipulation With PHP Config

    10/29

    and the output would change to look like this:

    name,Bruce Banner email,[email protected] host,mail.apollo.domain 

    You can write your configuration data in Windows INI file format with the following script,

  • 8/13/2019 [Developer Shed Network] Server Side - PHP - Configuration Manipulation With PHP Config

    11/29

    which produces this output:

    name=Bruce Banner [email protected] host=mail.apollo.domain 

    And finally, you can even write configuration data using the XML standard, with the XML type (note that thisrequires the presence of two other XML classes from PEAR, the Parser class and the Util class in order to work).Here' s the script,

  • 8/13/2019 [Developer Shed Network] Server Side - PHP - Configuration Manipulation With PHP Config

    12/29

    and here' s the output:

     Bruce Banner [email protected] mail.apollo.domain 

    If you know a little bit about XML, you' ll know that is not really well-formed XML, since the root element is missing.This can be easily rectified; just add an option specifying the name of this root element to the writeConfig(), asdone earlier with the PHPArray type. Here' s the revised script,

  • 8/13/2019 [Developer Shed Network] Server Side - PHP - Configuration Manipulation With PHP Config

    13/29

    and the revised, well-formed output:

      Bruce Banner [email protected] mail.apollo.domain  

    Array Of Hope

    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 theparseConfig() method discussed previously - the only difference is that where earlier you handed the method aPHP 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-valuepairs.

    Consider the following sample XML configuration file,

  • 8/13/2019 [Developer Shed Network] Server Side - PHP - Configuration Manipulation With PHP Config

    14/29

    and this next PHP script, which takes care of reading it and converting the data within it to a native PHP structure:

    Here' s the output:

    Array ( [root] => Array ( [mysql] => Array ( [host] => localhost [user] => joe [pass] => secret [db] => db456  )

     )

     )

    What happens here is pretty simple - the parseConfig() method reads the XML configuration file, parses it andplaces it into a private member of the object, and simultaneously exposes a root object that can be used to interactwith 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 fordisplay).

    If you want the value of a specific configuration variable (rather than the whole caboodle), it is simple to obtain itfrom the associative array created via toArray(),by drilling down to the appropriate key. Consider the followingrevision of the example above, which illustrates by retrieving the various configuration values and using them to

  • 8/13/2019 [Developer Shed Network] Server Side - PHP - Configuration Manipulation With PHP Config

    15/29

    connect to a MySQLdatabase:

  • 8/13/2019 [Developer Shed Network] Server Side - PHP - Configuration Manipulation With PHP Config

    16/29

    OOP purists will be pleased to hear that there' s also a more elegant method to retrieve data from a configurationfile - more on that on the next page.

    Up A Tree

    In addition to the technique described previously, the Config class also includes a number of built-in methods to

    retrieve configuration values from the internal stack after they have been read in. In order to understand thisalternative approach, you first need to conceptually understand how the Config class deals with a configurationfile, and with the various sections within it.

    Seen through the eyes of Config, every configuration file can be broken down into four basic elements:

    1. Sections - blocks within the configuration file, each with a name, containing one or more directives.

    2. Directives - variable-value pairs

    3. Comments - explanatory notes which can be ignored, these are meant only for human consumption

    4. Blanks - blank lines, useful for cleaning up the visual appearance of a configuration file

    The root object returned by the parseConfig() method is a section, and as such, it exposes a number of differentmethods. For the moment, we' ll focus on the getItem() method, used to return a reference to another section, to adirective, or to a comment. Once a reference is obtained to a directive or comment, other methods - the mostcommon one is getContent() - become available to retrieve the content of that directive or comment.

    In order to better understand how this works, consider the following example, which does exactly what theprevious example did, but uses object methods and properties to retrieve the various configuration values.

  • 8/13/2019 [Developer Shed Network] Server Side - PHP - Configuration Manipulation With PHP Config

    17/29

  • 8/13/2019 [Developer Shed Network] Server Side - PHP - Configuration Manipulation With PHP Config

    18/29

    If you' ve ever used the Document Object Model (DOM) in XML, the above probably looks strangely familiar to you.It should - the Config class uses a similar approach, providing methods to obtain references to different "nodes" ofthe configuration "tree", and thereby to retrieve the values of those nodes. Like the DOM, there are also methodsto add, edit and delete nodes - but those come later.

    A quick note on the getItem() method above - it can be used to return a reference to any section of theconfiguration file and requires, as first argument, one of the keywords "section", "directive", "comment" or "blank"(to identify the type of data needed) and, as second argument, an identifier to help it locate the necessary node. Anumber of different options can be sent as additional arguments to getItem() to help it identify the correct node -take a look at the manual for detailed information on this.

    Once a reference to the correct node has been obtained, the getContent() method can be used to retrieve itsvalue. This method may be used with both directives and comments.

    Here' s another example, this time using a Windows INI file like the one below,

    and the following script to retrieve mail server access information:

  • 8/13/2019 [Developer Shed Network] Server Side - PHP - Configuration Manipulation With PHP Config

    19/29

     

     

     

     

     

    This follows much the same logic as before - the getItem() method is used to first obtain a reference to the[Settings] section of the INI file, and then to the appropriate directives within that section. Once the variable valueshave been retrieved via the getContent() method, they are printed to the output device.

    Here' s the output:

    System is currently configured for POP account [email protected] and password guessme

    When retrieving configuration data in this manner, a number of utility methods are also available; these can come

  • 8/13/2019 [Developer Shed Network] Server Side - PHP - Configuration Manipulation With PHP Config

    20/29

    in handy in certain situations. Here' s a quick list:

    getName() - retrieves the item name

    getType() - retrieves the item type

    getParent() - retrieves a reference to the item' s parent

    getChild() - returns a reference to the item' s child

    getItemPosition() - returns the item' s position among its siblings

    countChildren() - returns a count of the item' s children

    Changing Things Around

    Just as you can getContent(), you can also setContent() - and this next example demonstrates how, by using thismethod to change a configuration variable read from a file.

  • 8/13/2019 [Developer Shed Network] Server Side - PHP - Configuration Manipulation With PHP Config

    21/29

    In this case, the setContent() method is used to change the value of a configuration variable, and then thewriteConfig() method is used to write the entire set of variables back to the file.

    This is one of the more common applications of the Config class - displaying the current configuration to the user,and saving modifications back - so pay attention to this next example, which builds on what you' ve just learned tocreate 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 acceptsthe new configuration and saves it to a file.

  • 8/13/2019 [Developer Shed Network] Server Side - PHP - Configuration Manipulation With PHP Config

    22/29

  • 8/13/2019 [Developer Shed Network] Server Side - PHP - Configuration Manipulation With PHP Config

    23/29

  • 8/13/2019 [Developer Shed Network] Server Side - PHP - Configuration Manipulation With PHP Config

    24/29

  • 8/13/2019 [Developer Shed Network] Server Side - PHP - Configuration Manipulation With PHP Config

    25/29

  • 8/13/2019 [Developer Shed Network] Server Side - PHP - Configuration Manipulation With PHP Config

    26/29

    Here' s what it looks like:

    [image]image1.gif[/image]

    Giving Birth

    The sharp-eyed amongst you would have noticed that the previous example made one important assumption: thatthe configuration file existed in the first place. If it didn' t, the code on the previous page would return an error - notsomething you want happening the first time your application is installed.

    With this in mind, the Config class also comes with a number of methods that allow you to create a completeconfiguration file from scratch. Consider the following example, which demonstrates:

  • 8/13/2019 [Developer Shed Network] Server Side - PHP - Configuration Manipulation With PHP Config

    27/29

    Here' s the output:

    [mail] name=Bruce Banner [email protected] host=mail.apollo.domain 

    In this case, an object of the Config_Container class is initialized as a section named "mail", and a reference isobtained to it. This reference is used to build the rest of the configuration tree via the createDirective() methods.Once the tree is complete, a call to setRoot() takes care of resetting the root reference to the newly-createdsection, and a call towriteConfig() writes the entire tree to the named file.

    In addition to the createDirective() method, the class also includes createSection(), createComment() andcreateBlank() methods, designed specifically to create sections, comments and blank lines respectively. Take alook at the manual pages for more on these methods, together with usage examples.

    Link Zone

    That' s about it for the moment. In this article, I introduced you to the Config class, which is designed primarily toassist you in the reading, writing and manipulation of configuration data. I showed you how to read and writeconfiguration files in XML, PHP and INI formats, how to create configuration files from scratch, and how to useConfig' s built-in methods to simplify and speed up Web-based configuration tool development.

    Of course, whatever you' ve seen over the past few pages is just the top of the iceberg. Config comes with a largenumber of different methods, allowing you to do all kinds of interesting things like creating configuration sectionsand variables from scratch, dynamically adding and removing variables from an existing configuration, shifting thepositions of sections and variables around within a file, and much more.

    If you' d like to learn more about Config and its related tools, you should take a look at the following links:

    The Config package on PEAR, at http://pear.php.net/Config

  • 8/13/2019 [Developer Shed Network] Server Side - PHP - Configuration Manipulation With PHP Config

    28/29

    The Config package on PEAR, at http://pear.php.net/Config

    Config API documentation, at http://pear.php.net/manual/en/package.configuration.config.intro.php

    The official PEAR Web site, at http://pear.php.net/ 

    Till next time...ciao!

    Note: Examples are illustrative only, and are not meant for a production environment. Examples in this tutorial

    have been tested on Linux/i586 with Apache 1.3.26, PHP 4.2 and Config 1.8. Melonfire provides no warranties orsupport for the source code described in this article. YMMV!

  • 8/13/2019 [Developer Shed Network] Server Side - PHP - Configuration Manipulation With PHP Config

    29/29

    This article copyright Melonfire 2000-2003. All rights reserved.