This package is abandoned and no longer maintained. No replacement package was suggested.

1.0.1 2018-09-08 17:32 UTC

This package is auto-updated.

Last update: 2020-12-05 14:21:44 UTC


README

Build Status codecov

VVatashi/DI

A simple and minimalistic implementation of the Dependency Injection Container in PHP7. Features:

  • Implements PSR-11;
  • Configuration in code;
  • Uses PHP class names as identifiers;
  • Uses constructor parameter injection using PHP type hints.

Install

With composer

composer require vvatashi/di

Usage

Configure container

Create a new container

$container = new \VVatashi\DI\Container();

Register a type using the factory function

When the specified type is requested from the container for the first time, the provided function will be called. This function should create an instance of a compatible type, may somehow configure it and return it.

This function gets the container itself as a single parameter, that can be used as a Service Locator.

$container->registerCallback(LoggerInterface::class, function ($container) {
    // Create the Monolog logger for example.
    $logger = new \Monolog\Logger('test');
    $handler = new \Monolog\Handler\StreamHandler('test.log');
    $logger->pushHandler($handler);
    return $logger;
});

Register a type using the type name

Suppose that you have the following types:

interface TestInterface {}
class TestClass implements TestInterface {
    public function __construct(LoggerInterface $logger) {
        $logger->log('Howdy world!');
    }
}

You can register the TestClass type to be instantiated, when the TestInterface is requested:

$container->registerType(TestInterface::class, TestClass::class);

The LoggerInterface then will be automatically resolved from the container and passed to the TestClass constructor.

Register a type using the instance

If you already have an instance of some type, you can register it directly:

$container->registerInstance(TestInterface::class, $instance);

Use container

You can use the $container->get('class name') method to use the container as a Service Locator and directly instantiate something from it.

However this is considered anti-pattern, as it strongly couples your code with the container.

In the most cases you should rely on the injection of the constructor parameters.