此包已被放弃,不再维护。作者建议使用 orno/di 包。

适用于PHP 5.3+的快速依赖注入容器

1.2.0 2013-08-04 22:55 UTC

This package is not auto-updated.

Last update: 2022-02-01 12:26:21 UTC


README

Build Status Dependencies Status Coverage Status Total Downloads Latest Stable Version

已弃用:使用 Orno\Di 替代,因为这两个包非常相似,而Orno的包发展更加活跃。

The League\Di 库为您的应用程序提供了一个快速且强大的依赖注入容器。

安装

通过 Composer

{
    "require": {
        "league/di": ">=1.1"
    }
}

使用方法

获取容器对象

include 'vendor/autoload.php';

$container = new League\Di\Container;

将具体类绑定到接口

$container->bind('\Foo\Bar\BazInterface', '\Foo\Bar\Baz');

自动依赖解析

Di 容器能够通过检查对象构造函数上的类型提示来递归解析对象及其依赖项。

namespace Foo\Bar;

class Baz
{
  public function __construct(Qux $qux, Corge $corge)
  {
    $this->qux = $qux;
    $this->corge = $corge;
  }

  public function setQuux(Quux $quux)
  {
    $this->quux = $quux;
  }
}

$container->resolve('\Foo\Bar\Baz');

定义参数

或者,您可以在实例化类时指定要注入的内容。

定义构造函数参数

$container->bind('\Foo\Bar\Baz')->addArgs(array('\Foo\Bar\Quux', '\Foo\Bar\Corge'));

$container->resolve('\Foo\Bar\Baz');

定义使用参数调用的方法

$container->bind('\Foo\Bar\Baz')->withMethod('setQuux', array('\Foo\Bar\Quux'));

$container->resolve('\Foo\Bar\Baz');

子容器和作用域解析

League\Di 的一个出色功能是它能够为子容器提供与父容器分开的解析作用域。如果您在一个容器中将具体类绑定到接口,您可以在子容器中重新绑定它,而不用担心会覆盖父容器中的原始绑定。

创建子容器

有两种方法可以创建子容器。

$child = $continer->createChild();

// OR

$child = new Container($container);

使用子容器

使用子容器的主要优势是作用域特定的解析。

$container->bind('FooInterface', 'Foo');

// Assuming class Bar has a FooInterface dependency.
// This would use the Foo implementation.
$bar = $container->resolve('Bar');

// ...
$child = $container->createChild();
$child->bind('FooInterface', 'Baz');

// And this would use the Baz implementation.
$bar = $child->resolve('Bar');

待办事项

  • 详细的文档

贡献

有关详细信息,请参阅 CONTRIBUTING

致谢

许可证

MIT 许可证 (MIT)。有关更多信息,请参阅 许可证文件