Skip to content

Instantly share code, notes, and snippets.

@trq
Created January 12, 2012 13:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save trq/1600497 to your computer and use it in GitHub Desktop.
Save trq/1600497 to your computer and use it in GitHub Desktop.
A simple PHP DI Container and Manager
<?php
class Foo
{
private $name;
public function __construct($name)
{
echo "Foo instantiated";
$this->name = $name;
}
public function say()
{
echo "Hello " . $this->name . "\n";
}
}
class AssetManager
{
private $assets;
public function set($name, Asset $asset)
{
$this->assets[$name] = $asset;
}
public function get($name)
{
return isset($this->assets[$name]) ? $this->assets[$name]->get() : null;
}
}
class Asset
{
private $params = array();
private $resource;
public function __set($key, $value)
{
$this->params[$key] = $value;
}
public function __get($key)
{
return isset($this->params[$key]) ? $this->params[$key] : null;
}
public function set(closure $callback)
{
$this->resource = $callback;
}
public function get()
{
$resource = $this->resource;
return $resource($this);
}
public function single(closure $callback)
{
return function ($c) use ($callback) {
static $object;
if (is_null($object)) {
$object = $callback($c);
}
return $object;
};
}
}
$a = new Asset;
$a->name = 'thorpe!';
$a->set($a->single(function($c) {
return new Foo($c->name);
}));
$am = new AssetManager;
$am->set('foo', $a);
$am->get('foo')->say();
$am->get('foo')->say();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment