Skip to content

Instantly share code, notes, and snippets.

@sword-jin
Last active August 31, 2015 09:06
Show Gist options
  • Save sword-jin/c49251b41bd2c9a049e2 to your computer and use it in GitHub Desktop.
Save sword-jin/c49251b41bd2c9a049e2 to your computer and use it in GitHub Desktop.
简单的 Ioc 测试
<?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);
<?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.");
}
}
<?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