I tend to use a Settings static class in PHP, this is because
- It has a global scope
- You can enable / disable changes to protected configs
- You can add any settings during anywhere within runtime.
- You can make the class automated to fetch public configs from a file / DB.
Example:
abstract class Settings
{
static private $protected = array(); //For DB / Passwords etc
static private $public = array(); //For all public strings such as meta stuff for site
public static function getProtected($key)
{
return isset(self::$protected[$key]) ? self::$protected[$key] : false;
}
public static function getPublic($key)
{
return isset(self::$public[$key]) ? self::$public[$key] : false;
}
public static function setProtected($key,$value)
{
self::$protected[$key] = $value;
}
public static function setPublic($key,$value)
{
self::$public[$key] = $value;
}
public function __get($key)
{//$this->key // returns public->key
return isset(self::$public[$key]) ? self::$public[$key] : false;
}
public function __isset($key)
{
return isset(self::$public[$key]);
}
}
Then within your runtime, if you loaded this file first, followed by your database config file, your database config file would look like so:
<?php
Settings::setProtected('db_hostname','localhost');
Settings::setProtected('db_username','root');
Settings::setProtected('db_password','');
Settings::setProtected('db_database','root');
Settings::setProtected('db_charset','UTF-8');
//...
echo Settings::getProtected('db_hostname'); //localhost
//...
Settings::setPublic('config_site_title','MySiteTitle');
Settings::setPublic('config_site_charset','UTF-8');
Settings::setPublic('config_site_root','http://localhost/dev/');
?>
As you can see the we have a method __get
that should only be allowed to grab public variables, An example of why we have this is as follows:
$Template = new Template();
$Template->Assign('settings',new Settings());
Regardless the fact that we have used this object as a static object, the values should still stand so within the template you can now do, lets say.
<html>
<head>
<?php echo isset($settings->config_site_title) ? $settings->config_site_title : 'Fallback Title'?>
</head>
</html>
And this will only allow you to have access to the public data during the initialized period.
This can get a lot more complex but more system friendly, some examples:
- A
LoadConfig
method to automatically parse a config file, xml,php,yaml
- if you register an
shutdown_function
you can auto update the DB with new settings.
- you can auto populated the class with config from that database
- you can implement iterator's to make it compatible with looping
- Lots mroe.
This too me is by far the best methods to complete this job.