niletphp/dependency-container

NiletPHP 依赖注入容器。

v1.0.0 2018-04-21 10:13 UTC

This package is not auto-updated.

Last update: 2024-09-29 02:34:06 UTC


README

提供了一种简单方式来管理 PHP 项目的依赖项的依赖容器。

要求

PHP >= 7.0

安装

Composer

{
    "require": {
        "niletphp/dependency-container": ">=v1.0"
    }
}

示例

$dc = new Nilet\Components\Container\DependencyContainer();

解决给定具体项的依赖项并返回其新实例

$dc->create("Nilet\Foo");

绑定具体项到接口。解决此类绑定将始终返回新的具体实例

$dc->bind("Nilet\FooInterface", "Nilet\Foo");
$dc->bind("Nilet\FooInterface", function ($dc) {
    return new Nilet\Foo();
});
$dc->create("Nilet\FooInterface");

共享具体项(单例)。

$dc->share("Nilet\Foo");
$dc->share("Nilet\Foo", function ($dc) {
    return new Nilet\Foo();
});

将具体项(单例)绑定到接口

$dc->bindShared("Nilet\FooInterface", "Nilet\Foo");
$dc->bindShared("Nilet\FooInterface", function ($dc) {
    return new Nilet\Foo();
});

注册具体实例(单例)。

$foo = new Nilet\Foo();
$dc->instance("Nilet\Foo", $foo);

获取具体项。

$dc->get("Nilet\Foo");

$dc->bindShared("Nilet\FooInterface", "Nilet\Foo");
$dc->get("Nilet\FooInterface");

确定给定的具体项(单例)是否已解决。

$dc->bindShared("Nilet\FooInterface", "Nilet\Foo");
$dc->get("Nilet\FooInterface");
if ($dc->isResolved("Nilet\FooInterface")) { // evaluates to true
    // do something
} else {
    // do something else
}

确定给定的具体项是否共享。

$dc->share("Nilet\Foo");
if ($dc->isShared("Nilet\Foo")) { // evaluates to true
    // do something
} else {
    // do something else
}

确定给定的接口是否已绑定。

$dc->bind("Nilet\FooInterface", "Nilet\Foo");
if ($dc->isBound("Nilet\FooInterface")) { //evaluates to true
    // do something
} else {
    // do something else
}

确定给定的接口是否已绑定/共享。

$dc->bindShared("Nilet\FooInterface", "Nilet\Foo");
if ($dc->isBoundShared("Nilet\FooInterface")) { //evaluates to true
    // do something
} else {
    // do something else
}