slightly-interactive/di-container

A dependency injection container.

1.0.1 2021-01-26 19:14 UTC

This package is auto-updated.

Last update: 2024-11-27 03:36:41 UTC


README

Overview

DI Container is a PSR-11 compliant auto-wiring Dependency Injection container.

Usage

Instantiate the container:

use SlightlyInteractive\DI;

$container = new Container();

Resolve classes:

$myClass = $container->get(MyClass::class);

By default, the container will pass the exact same instance every time the same class is requested.

You can tell the container to create a new instance every time a given class is requested:

$container->set(MyClass::class)->factory();

Or when you instantiate the container you can tell it to create a new instance every time, for every class:

$container = new Container(Container::INSTANTIATE_FACTORY);

And then you can tell it to make specific classes use a single instance:

$container->set(MySingleton::class)->singleton();

You can map interfaces to a particular concrete instance:

$container->set(MyInterface::class)->map(MyClass::class);

You can do this for a particular class:

class MyDependent
{
    public function __construct(
        RealClass $realClass,
        MyInterface $myInterface
    ) {
        ...
    }
    
    ...
}

$container->set(MyDependent::class)
    ->argument('myInterface', MyClass::class);
    

You can use the argument parameter to pass non-object values to arguments, too:

class MyDependent
{
    public function __construct(
        RealClass $realClass,
        string $apiKey
    ) {
        ...
    }
    
    ...
}

$container->set(MyDependent::class)
    ->argument('apiKey', $_ENV['API_KEY']);