midnight/automatic-di

PHP 的自动依赖注入

1.2.0 2021-04-08 20:55 UTC

This package is auto-updated.

Last update: 2024-08-29 04:47:05 UTC


README

Build Status

此包为 PHP 提供自动依赖注入功能。它需要一个与 container-interop 兼容的容器。

安装

Composer: midnight/automatic-di

用法

假设我们有以下接口和类

interface FooInterface {
}

class Foo {
    private $bar;
    public function __construct(Bar $bar) {
        $this->bar = $bar;
    }
}

class Bar {
}

interface BazInterface {
}

class Baz {
}

class Hodor {
    private $baz;
    public function __construct(BazInterface $baz) {
        $this->baz = $baz;
    }
}

现在我们可以这样使用 AutomaticDiContainer

$wrappedContainer = new Some\Other\Container; // An implementation of Interop\Container\ContainerInterface
$config = Midnight\AutomaticDi\AutomaticDiConfig::fromArray([
    'preferences' => [
        FooInterface::class => Foo::class,
    ],
    'classes' => [
        Hodor::class => [
            'baz' => Baz::class,
        ],
    ],
]);
$container = new Midnight\AutomaticDi\AutomaticDiContainer($wrappedContainer, $config);

$foo = $container->get(FooInterface::class); // Returns an instance of Foo
$hodor = $container->get(Hodor::class); // Returns an instance of Hodor with an injected Baz

性能

此包通过反射工作。这不会很慢吗?

是的,确实如此。很快将提供缓存。