Created
January 5, 2015 21:53
-
-
Save felipecwb/d5907f56e26bac76c866 to your computer and use it in GitHub Desktop.
Simple Data Container
This file contains 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 | |
namespace Felipecwb\Sample; | |
class Container | |
{ | |
private $maps = []; | |
public function __call($identity, array $arguments) | |
{ | |
if (strpos($identity, 'get') !== 0 && strlen($identity) <= 3) { | |
throw new \BadMethodCallException("Method '{$identity}' does not exists!"); | |
} | |
$identity = substr($identity, 3); | |
return $this->get($identity); | |
} | |
public function set($identity, $data) | |
{ | |
$identity = ucfirst($identity); | |
if ($data instanceof \Closure) { | |
$data = $data($this); | |
} | |
$this->maps[$identity] = $data; | |
} | |
public function get($identity) | |
{ | |
$identity = ucfirst($identity); | |
if (! array_key_exists($identity, $this->maps)) { | |
throw new \LogicException("Identity: " . $identity . " not exists!"); | |
} | |
return $this->maps[$identity]; | |
} | |
} |
This file contains 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 | |
use Felipecwb\Sample\Container; | |
$container = new Container(); | |
$container->set('message', "Tests..." . PHP_EOL); | |
$container->set('config', function ($c) { | |
return [ | |
'environment' => 'dev', | |
'message' => $c->get('message') | |
]; | |
}); | |
echo $container->getMessage(); // Tests... | |
print_r($container->getConfig()); // Array([environment] => dev, [message] => Tests...) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment