ntentan/panie

为 NtentanFX 定制的轻量级 DI 容器

v0.8.0 2024-06-23 07:15 UTC

This package is auto-updated.

Last update: 2024-09-18 01:34:12 UTC


README

Tests Scrutinizer Code Quality Code Coverage Latest Stable Version Total Downloads

一个与 PSR-Container 兼容的依赖注入容器,专为在 ntentan 框架中使用而构建。然而,就像框架中的其他组件一样,ntentan 并不是 panie 运作所必需的。Panie 可以作为一个独立的依赖注入容器来使用。

用法

要创建容器实例,我们使用

<?php
require "vendor/autoload.php";
$container = new ntentan\panie\Container();
$fooInstance = $container->resolve(Foo::class);

Panie 将创建 Foo 类的实例,并自动注入类型提示的依赖项,如果我们的 Foo 类定义如下

<?php
class Foo
{
    private $bar;

    public function __constructor(Bar $bar) {
        $this->bar = $bar;
    }
}

配置

在我们想要提供特定连接的情况下,我们可以通过提供在解析类类型时使用的选项来配置容器。

例如,在我们的 Foo 类需要一个 BarInterface 接口,并且我们特别想要 BarImplementation 类的情况下,我们可以按照以下方式连接容器

<?php
require "vendor/autoload.php";
$container = new ntentan\panie\Container();
$container->bind(BarInterface::class)->to(BarImplementation::class);
$fooInstance = $container->get(Foo::class);

容器还可以接受一个工厂函数,该函数返回所需类型的实例。

<?php
require "vendor/autoload.php";
$container = new ntentan\panie\Container();
$container->bind(BarInterface::class)->to(function(){
    return new BarImplementation();
});

您还可以通过指定绑定类型时的单例标志来让容器维护特定服务的内部单例。

<?php
require "vendor/autoload.php";
$container = new ntentan\panie\Container();
$container->bind(BarInterface::class)->to(BarImplementation::class)->asSingleton();
$fooInstance = $container->get(Foo::class);

除了 bindto 函数外,容器还有一个 setup 函数,它接受一个包含容器连接信息的关联数组。在这种情况下,可能的连接可以是 ...

$container->setup([
    BarInterface::class => BarImplementation::class
]);

... 或者对于单例和工厂 ...

$container->setup([
    BarInterface::class => [function(){ ... }, 'singleton' => true]
]);