Skip to content

Instantly share code, notes, and snippets.

@felipecwb
Created January 5, 2015 21:53
Show Gist options
  • Save felipecwb/d5907f56e26bac76c866 to your computer and use it in GitHub Desktop.
Save felipecwb/d5907f56e26bac76c866 to your computer and use it in GitHub Desktop.
Simple Data Container
<?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];
}
}
<?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