Skip to content

Instantly share code, notes, and snippets.

@etki
Last active August 29, 2015 14:05
Show Gist options
  • Save etki/f8df18316ea25d1bddda to your computer and use it in GitHub Desktop.
Save etki/f8df18316ea25d1bddda to your computer and use it in GitHub Desktop.
simple string-based array access
<?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;
}
}
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