Created
January 12, 2012 13:23
-
-
Save trq/1600497 to your computer and use it in GitHub Desktop.
A simple PHP DI Container and Manager
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 | |
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