Configuration variables via Singleton object in PHP4

There is probably no design pattern handier and easier to set up than a Singleton pattern. One of the best uses in PHP apps is for configuration variables. You can use define all over the place or you can use $GLOBAL but things work a lot better when you have nice neat place to set and get global configuration variables. Enter the Singleton Configuration object. Here's some simple code for the object itself, simply named Config.php:

PHP:
  1. <?php
  2.  
  3. /**
  4. * Web Config object using Singleton pattern
  5. *
  6. * @author Rich Zygler, Jr.
  7. * @datecreated 03/08/2005
  8. * @access public
  9. * @usage $config =& Config::getInstance();
  10. * @usage $config->setConfig('admin_email', 'test@test.com');
  11. * @usage $email = $config->getConfig('admin_email');
  12. * @TODO
  13. */
  14.  
  15. class Config
  16. {
  17.  
  18.   var $configVars = array();
  19.  
  20.  
  21.   /*
  22.    * Create a new config object
  23.    */
  24.  
  25.   function &getInstance()
  26.   {
  27.     static $instance;
  28.     if (!$instance)
  29.     {
  30.       $instance = array(new Config);
  31.     }
  32.     return $instance[0];
  33.   }
  34.  
  35.  
  36.   /*
  37.    * Get config data
  38.    *
  39.    * @param     $key string - array key of variable whose data we are retrieving
  40.    * @return    $this->configVars string
  41.    */
  42.   function getConfig($key)
  43.   {
  44.     return $this->configVars[$key];
  45.   }
  46.  
  47.  
  48.   /*
  49.    * Set config data
  50.    *
  51.    * @param     $key string -variable to retrieve data stored
  52.    * @param     $value string -variable that contains data to store
  53.    * @return    true
  54.    * Can use arrays as well as in  $config->setConfig('email_list', array(//... ));
  55.    * retrieve array by foreach($config->getConfig('email_list') as $email) { //... }
  56.    *
  57.    */
  58.  
  59.   function setConfig($key, $val)
  60. {
  61.     $this->configVars[$key] = $val;
  62.     return true;
  63.   }
  64.  
  65. }
  66.  
  67. ?>

If you think the getInstance method looks a little borked, you're right. What we're doing there is attempting to return the first and only the first implementation of this object. So everytime you make a call to this config object, you should be getting the same one. That's why we return the [0]th item in the array. This is a little easier in PHP5 but for PHP4, this is what we're stuck with.

And here's how to use this bad boy:

PHP:
  1. <?php
  2. /**
  3. * config include
  4. *
  5. * @author Rich Zygler, Jr.
  6. * @datecreated 03/08/2005
  7. * @TODO
  8. */
  9.  
  10. // Bring in the Config class file
  11. require_once ('Config.php');
  12.  
  13. // Instantiate our config object
  14. // Remember in PHP4, we use the  =&
  15. // to pass by reference
  16.  
  17. $config =& Config::getInstance();
  18.  
  19. // Set up some config vars
  20. // will change per application
  21. // The usage here is:     setConfig(varName, varValue)
  22.  
  23. $config->setConfig('appVersion', '1.o');
  24. $config->setConfig('appName','Tester');
  25. $config->setConfig('debug', true);
  26.  
  27. // Maybe set the DB connection vars
  28. $config->setConfig('dbconn', array(
  29.                                         'username' => 'bunsen',
  30.                                         'password' => '!honeydew%',
  31.                                         'host'     => 'localhost',
  32.                                         'db'       => 'test',
  33.                                         'type'     => 'mysql'
  34.                                   )
  35.                   );
  36.  
  37. // Now to get those values back from the $config object
  38.  
  39. // first let's initialize our vars
  40. $appVersion = '';
  41. $appName = '';
  42. $debug = false;
  43. $dbConnArray = array(); // used for getting back db values
  44. $dbUser = '';
  45. $dbPass = '';
  46. $dbHost = '';
  47. $dbType = '';
  48. $dbName = '';
  49.  
  50. // Now let's get the values from the config object and populate our variables
  51. // of course, for a fully functioning app, you may want to check that these values are set
  52. $appVersion = $config->getConfig('appVersion');
  53. $appName = $config->getConfig('appName');
  54. $debug = $config->getConfig('debug');
  55.  
  56. // Here, we slurp the whole array from the config into a new array
  57. $dbConnArray = $config->getConfig('dbconn');
  58. $dbUser     = $dbConnArray['username'];
  59. $dbPass     = $dbConnArray['password'];
  60. $dbHost     = $dbConnArray['host'];
  61. $dbType     = $dbConnArray['type'];
  62. $dbName     = $dbConnArray['db'];
  63.  
  64. // Now let's echo everything out to make sure the values are
  65. // coming back correctly   
  66. echo "The version is: <b>$appVersion</b> <br />";
  67. echo "The name is: <b>$appName</b> <br />";
  68. echo "The debugger is on: <b>$debug</b> (1 = true)<br />";
  69. echo "The db username is: <b>$dbUser</b> <br />";
  70. echo "The db password is: <b>$dbPass</b> <br />"
  71.  
  72. ?>

What's great about this method of doing things is that you virtually eliminate the need for global variables in functions and objects. This is a very good thing. If you need some configuration variables available to a function or object, you can pass it this config object like this:

PHP:
  1. // call the function this way
  2. doSomethingWithConfig($config);
  3.  
  4. // define the function this way
  5. // Remember to accept the object by reference (add the &)
  6. // otherwise a copy of the config data is created -- not good
  7.  
  8. function doSomethingWithConfig(&$config)
  9. {
  10.      // get app version
  11.     $appVersion = '';
  12.     $appVersion = $config->getConfig('appVersion');
  13.     return $appVersion;
  14. }

If you like this way of doing things, wait until you try to recreate this in PHP5, it's even easier.

Post a Comment

Close
E-mail It