midnight/automatic-di

automatic dependency injection for PHP

1.2.0 2021-04-08 20:55 UTC

This package is auto-updated.

Last update: 2024-03-29 03:43:49 UTC


README

Build Status

This package provides automatic dependency injection for PHP. It requires a container-interop-compatible container.

Installation

Composer: midnight/automatic-di

Usage

Let's say we have the following interfaces and classes:

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;
    }
}

Now we can use the AutomaticDiContainer like this:

$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

Performance

This package works via reflection. Isn't that slow?

Yes, it is. A cache is coming soon.