From 1b233062589a53f5a6a296d065de1616cd4dd2df Mon Sep 17 00:00:00 2001 From: Andrey Kutejko Date: Tue, 17 Dec 2013 21:35:30 +0200 Subject: [PATCH] dependency injection container --- src/container.php | 66 +++++++++++++++++++++++++++++++++++++++++++++ t/ContainerTest.php | 24 +++++++++++++++++ 2 files changed, 90 insertions(+) create mode 100644 src/container.php create mode 100644 t/ContainerTest.php diff --git a/src/container.php b/src/container.php new file mode 100644 index 0000000..6859be7 --- /dev/null +++ b/src/container.php @@ -0,0 +1,66 @@ +values)) + throw new InvalidArgumentException('Identifier "'.$id.'" is not defined.'); + + $v = $this->values[$id]; + if ($v[0] == 'function') { + return call_user_func_array($v[1], $args); + } elseif ($v[0] == 'factory') { + $value = call_user_func_array($v[1], $args); + $this->values[$id] = array('value', $value); + return $value; + } else /*value*/ { + return $v[1]; + } + } + + public function get() + { + $args = func_get_args(); + $id = array_shift($args); + return $this->getWithArgs($id, $args); + } + + public function __call($name, $args) + { + switch ($name) { + case 'set': + $this->values[$args[0]] = array('value', $args[1]); + break; + case 'setFunction': + $this->values[$args[0]] = array('function', $args[1]); + break; + case 'setFactory': + $this->values[$args[0]] = array('factory', $args[1]); + break; + default: + return $this->getWithArgs($name, $args); + } + } + + private static $instance = null; + + public static function getInstance() + { + if (!self::$instance) + self::$instance = new self; + return self::$instance; + } + + public static function __callStatic($name, $args) + { + return call_user_func_array(array(self::getInstance(), $name), $args); + } +} + diff --git a/t/ContainerTest.php b/t/ContainerTest.php new file mode 100644 index 0000000..1948e68 --- /dev/null +++ b/t/ContainerTest.php @@ -0,0 +1,24 @@ +assertEquals('Hello, World', \PFF\Container::text()); + } + + public function testFunction() + { + \PFF\Container::setFunction('wrap', function($str) { return '('.$str.')'; }); + $this->assertEquals('(i love lisp)', \PFF\Container::wrap('i love lisp')); + } + + public function testFactory() + { + \PFF\Container::setFactory('wrapOnce', function($str) { return '('.$str.')'; }); + $this->assertEquals('(i love lisp)', \PFF\Container::wrapOnce('i love lisp')); + $this->assertEquals('(i love lisp)', \PFF\Container::wrapOnce('i hate lisp')); + } +} + -- 2.49.0