Skip to content

Instantly share code, notes, and snippets.

@omerucel
Created March 3, 2014 00:00
Show Gist options
  • Select an option

  • Save omerucel/9315924 to your computer and use it in GitHub Desktop.

Select an option

Save omerucel/9315924 to your computer and use it in GitHub Desktop.
Config class with dot notation support.
<?php
/**
* $configs = array(
* 'app' => array(
* 'tmp_dir' => '/tmp',
* 'db' => array(
* 'database' => 'abc
* )
* )
* );
* $config = new Config($configs);
*
* echo $config->get('app.db.database'); // abc
*
* $config->set('app.tmp_dir', '/usr/tmp');
* echo $config->get('app.tmp_dir'); // /usr/tmp
*
* var_dump($config->get('app')) // object..
*/
class Config
{
/**
* @var array
*/
protected $data;
/**
* @param array $data
*/
public function __construct(array $data = array())
{
$this->data = json_decode(json_encode($data));
}
/**
* @param $key
* @param null $default
* @return mixed
*/
public function get($key, $default = null)
{
$value = &$this->data;
foreach (explode('.', $key) as $step) {
$value = &$value->{$step};
}
if ($value === null) {
return $default;
}
return $value;
}
/**
* @param $key
* @param $value
*/
public function set($key, $value)
{
$oldValue = &$this->data;
foreach (explode('.', $key) as $step) {
$oldValue = &$oldValue->{$step};
}
$oldValue = $value;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment