flashytime/container

一个轻量级的PHP依赖注入容器。

v1.0.0 2018-07-11 13:33 UTC

This package is not auto-updated.

Last update: 2024-09-27 10:02:40 UTC


README

一个轻量级的PHP依赖注入容器。

安装

composer require flashytime/container

使用

创建容器
use Flashytime\Container\Container;
$container = new Container();
注册闭包
$this->container->set('hello', function () {
    return 'Hello World!';
});
echo $this->container->get('hello'); //Hello World!
$this->container->set('name', function () {
    return 'Mocha';
});
$this->container->set('mocha', function ($container) {
    return sprintf('Hello %s!', $container->get('name'));
});
echo $this->container->get('mocha'); //Hello Mocha!
注册实例或类
$this->container->set('foo', function () {
    return new Foo();
});

或者

$this->container->set('foo', new Foo());

或者

$this->container->set('foo', 'Flashytime\Container\Tests\Foo');

或者

$this->container->set('foo', Flashytime\Container\Tests\Foo::class);
获取条目
$this->container->get('foo');
注册单例
$this->container->setSingleton('foo', Flashytime\Container\Tests\Foo::class);
$first = $this->container->get('foo');
$second = $this->container->get('foo');
var_dump($first === $second); //true
依赖注入
interface FooInterface
{

}

class Foo implements FooInterface
{
    private $name;
    private $age;

    public function __construct($name = null, $age = 0)
    {
        $this->name = $name;
        $this->age = $age;
    }

    public function setName($name)
    {
        $this->name = $name;
    }

    public function getName()
    {
        return $this->name;
    }

    public function setAge($age)
    {
        $this->age = $age;
    }

    public function getAge()
    {
        return $this->age;
    }
}

class Bar
{
    public $foo;

    public function __construct(FooInterface $foo)
    {
        $this->foo = $foo;
    }

    public function getFoo()
    {
        return $this->foo;
    }
}
$this->container->set(FooInterface::class, Foo::class);
$this->container->set('bar', Bar::class);
$bar = $this->container->get('bar');
var_dump($bar instanceof Bar); //true
var_dump($bar->getFoo() instanceof Foo); //true

查看测试以获取更多用法。

许可证

MIT