rrylee
8/31/2015 - 9:02 AM

简单的 Ioc 测试

简单的 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

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'));
    }
}
<?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.");
    }
}