Last active
August 29, 2015 14:05
-
-
Save etki/f8df18316ea25d1bddda to your computer and use it in GitHub Desktop.
simple string-based array access
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 | |
class Config | |
{ | |
protected $data; | |
public function __construct(array $data) | |
{ | |
$this->data = $data; | |
} | |
public function get($alias) | |
{ | |
$keys = explode('.', $alias); | |
$data = $this->data; | |
foreach ($keys as $key) { | |
if (empty($key)) { | |
throw new \InvalidArgumentException('Empty key provided'); | |
} | |
if (!isset($data[$key])) { | |
$message = sprintf( | |
'Key %s hasn\'t been found in config', | |
$key | |
); | |
throw new \BadMethodCallException($message); | |
} | |
$data = $data[$key]; | |
} | |
return $data; | |
} | |
} |
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
require 'Config.php'; | |
$data = array( | |
'app' => array( | |
'params' => array( | |
'db' => array( | |
'user' => 'underdog', | |
), | |
), | |
), | |
); | |
$config = new Config($data); | |
var_dump($config->get('app.params.db.user'), $config->get('app.params')); | |
/* | |
string(8) "underdog" | |
array(1) { | |
'db' => | |
array(1) { | |
'user' => | |
string(8) "underdog" | |
} | |
} | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment