Last active
August 31, 2015 09:06
-
-
Save sword-jin/c49251b41bd2c9a049e2 to your computer and use it in GitHub Desktop.
简单的 Ioc 测试
This file contains hidden or 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 | |
require 'Ioc.php'; | |
class Foo | |
{ | |
private $bar; | |
public function __construct(Bar $bar) | |
{ | |
$this->bar = $bar; | |
} | |
} | |
class Bar{} | |
Ioc::bind('Foo', function() { | |
return new Foo(new Bar); | |
}); | |
$foo = Ioc::make('Foo'); | |
var_dump($foo); |
This file contains hidden or 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 Ioc | |
{ | |
protected static $registry = []; | |
public static function bind($name, Callable $resolver) | |
{ | |
static::$registry[$name] = $resolver; | |
} | |
public static function make($name) | |
{ | |
if (isset(static::$registry[$name])) { | |
$resolver = static::$registry[$name]; | |
return $resolver(); | |
} | |
return new Exception("$name not registered."); | |
} | |
} |
This file contains hidden or 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 | |
require 'Ioc.php'; | |
class Foo {} | |
class IocTest extends PHPUnit_Framework_TestCase | |
{ | |
public function test_ioc_work() | |
{ | |
Ioc::bind('Foo', function() { | |
return new Foo; | |
}); | |
$this->assertInstanceOf('Foo', Ioc::make('Foo')); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment