A singleton class to keep all settings for a site in one place.
class Settings {
private static $singleton = null;
private $settings = array();
private function __construct() {
$this->load();
}
public static function getInstance() {
if(self::$singleton == null)
self::$singleton = new Settings();
return self::$singleton;
}
public function get($key) {
if(substr($key, 20) == "site.url.currentpage") {
return "$_SERVER[PHP_SELF]?$_SERVER[QUERY_STRING]";
}else if(substr($key, 5) == "user.")
return $_SESSION[$key];
else
return $this->settings[$key];
}
public function set($key, $value) {
if(substr($key, 5) == "user.")
$_SESSION[$key] = $value;
else
$this->settings[$key] = $value;
$this->save();
}
public function load() {
//populate settings array here;
$this->settings["site.url"] = "http://whoyouknow.co.uk";
$this->settings["site.url.index"] = $this->settings["site.url"] . "index.php";
$this->settings["site.dir"] = "/public_html/whoyouknow.co.uk/";
$this->settings["site.dir.index"] = $this->settings["site.dir"] . "index.php";
$this->settings["site.baseurl"] = 2;
}
public function save() {
//save settings array here;
}
public function url($key, $params="") {
$url = $this->get($key);
if(!is_array($params)) { $params = func_get_args(); array_shift($params); }
if(!strpos($url, "?") && count($params) > 0) $url .= "?";
foreach($params as $param) {
$url .= $param;
if(++$i != count($params)) $url .= "&";
}
return $url;
}
public function urlVar($offset, $baseurl="") {
$baseurl = either($baseurl, $this->get("site.baseurl"), 1);
$url = explode("/", $_SERVER[REQUEST_URI]);
return $url[$baseurl + $offset];
}
}
echo Settings::getInstance()->get("site.url");
echo "<br />";
echo Settings::getInstance()->url("site.url", "id=23", "page=test");
echo "<br />";
echo Settings::getInstance()->urlVar(1); //(url e.g. http://whoyouknow.co.uk/uni/settings.php/test/)
echo "<br />";
Settings::getInstance()->set("user.name", "James");
echo Settings::getInstance()->get("user.name");
Output
http://whoyouknow.co.uk http://whoyouknow.co.uk?id=23&page=test test James
Motives:
Keep all site settings in one place.
Provide user info and general settings from that one place.
Map URL key's to actual URLs to allow easy changing of URLs - no hardcoded URLs
Usage:
echo Settings::get($key);
Hierarchical key structure:
site.url http://whoyouknow.co.uk
site.url.index http://whoyouknow.co.uk/index.php
site.url.blog http://whoyouknow.co.uk/blog/
site.url.images http://whoyouknow.co.uk/images/
Corresponding dir/url keys:
site.dir /public_html/
site.dir.index /public_html/index.php
site.dir.blog /public_html/blog/
site.dir.images /public_html/images/
User info by same method - transparently uses sessions for user info
user.id
user.name
user.email etc
A url function:
Settings::url("site.url.blog", "id=1234", "user_id=25")
Settings::url("site.url.currentpage")
requires function: mixed either(mixed, mixed [, ..., ...])
Back