Skip to content

Instantly share code, notes, and snippets.

@heatxsink
Created January 16, 2011 20:14
Show Gist options
  • Save heatxsink/782111 to your computer and use it in GitHub Desktop.
Save heatxsink/782111 to your computer and use it in GitHub Desktop.
<?php
class Config {
protected static $instance;
protected function __clone() {
}
public static function get() {
if (self::$instance === null) {
$class = __CLASS__;
self::$instance = new $class;
}
return self::$instance;
}
public static function base($vars) {
return self::get()->vars = $vars;
}
public static function set($key, $value) {
if (strpos($key, '.') !== false) {
$explode = explode('.', $key);
$endcode = end($explode); // fetch last keyset
unset($explode[count($explode) - 1]); // unset last keysey
$array =& self::get()->vars;
$current =& $array;
foreach ($explode as $key) {
if (isset($current[$key])) {
$current =& $current[$key];
} else {
$current[$key] = array();
$current =& $current[$key];
}
}
$current[$endcode] =& $value;
return $current;
} else {
return self::get()->inject(array($key => $value));
}
}
public static function key($key) {
if (strpos($key, '.') !== false) {
$explode = explode('.', $key);
$current = isset(self::get()->vars[$explode[0]]) ? self::get()->vars[$explode[0]] : false;
if (is_array($current)) {
unset($explode[0]);
foreach ($explode as $key) {
if (isset($current[$key])) {
$current = $current[$key];
} else {
$current = false;
}
}
}
return $current;
} else {
return self::get()->{$key};
}
}
public $vars = array();
public function clean() {
unset($this->vars);
$this->vars = array();
}
public function inject(array $vars) {
$this->vars = array_merge($this->vars, $vars);
return $this;
}
public function dump() {
ob_start();
print_r($this->vars);
return ob_get_clean();
}
public function get_array() {
return $this->vars;
}
public function __set($k, $v) {
$this->vars[$k] = $v;
}
public function __get($k) {
if (isset($this->vars[$k])) {
return $this->vars[$k];
} else {
return null;
}
}
public function __isset($k) {
return isset($this->vars[$k]);
}
public function __unset($k) {
unset($this->vars[$k]);
}
}
// set base array with config variables
Config::base($this->config);
// simple method of using:
Config::key('app.settings');
// or ...
$config = Config::get();
$config->app['settings'];
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment