kambo/deinj

Dependency injection container

v0.0.1 2017-12-27 19:27 UTC

This package is auto-updated.

Last update: 2024-11-19 16:47:04 UTC


README

Build Status Scrutinizer Code Quality Code Coverage Software License

Just another simple dependency injection container with following highlights:

  • Support of PSR-11 - Container interface

Install

Prefered way to install library is with composer:

composer require kambo/deinj

Usage

use Kambo\Deinj\Container;

use Kambo\Examples\Deinj\Transport;
use Kambo\Examples\Deinj\Mailer;
use Kambo\Examples\Deinj\UserManager;

// Create instance of the container.
$container = new Container;

// Set object factory method for identifier 'transport'.
$container->set(
    'transport',
    // Factory method is plain callback.
    function () {
        return new Transport();
    }
);

// Set object factory method for identifier 'mailer'.
$container->set(
    'mailer',
    // Factory method is plain callback. An instance of the container must be passed inside
    // the closure for allowing of the 'transport' injection.
    function ($container) {
        return new Mailer($container->get('transport'));
    }
);

// Set object factory method for identifier 'userManager'.
$container->set(
    'userManager',
    // Factory method is plain callback. An instance of the container must be passed inside
    // the closure for allowing of the 'mailer' injection.
    function ($container) {
        return new UserManager($container->get('mailer'));
    }
);

// Get instance of the UserManager service.
$userManager = $container->get('userManager');

// Call register method in the UserManager service.
$userManager->register('username', 'password');

License

The MIT License (MIT), https://opensource.org/licenses/MIT