Created
March 3, 2014 00:00
-
-
Save omerucel/9315924 to your computer and use it in GitHub Desktop.
Config class with dot notation support.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?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