3.0.4 2024-02-20 12:11 UTC

This package is auto-updated.

Last update: 2024-05-20 12:40:34 UTC


Latest Version on Packagist Software License

PHP dependency injection / factory.


Via Composer

$ composer require vakata/di


namespace test;

$di = new \vakata\di\Container();

interface I { }
class A implements I {}
class B {
    public function __construct(I $instance) { }
class C {
    public function __construct($firstParam, $secondParam) { }
    public function test($arg = 1) { return 1; }

// this will register class A, and an alias I for class A as the class implements that interface
$di->instance('\test\B'); // a B instance is created

// when registering you can prevent interfaces being added as aliases as adding the aliases manually
$di->register('\test\B', ['aliasedB']);

// you can also pass default constructor params, which can be named
$di->register('\test\C', null, ['secondParam' => 1, 2]);
$di->instance('\test\C'); // this will invoke \test\C::__construct(2,1);
$di->instance('\test\C', [2,4]); // this will invoke \test\C::__construct(2,4);

// you can also register instances:
$d = new D();
$di->register($d); // this is the same as \test\D

// you can also make sure that there is only one instance of a given class
$di->register('\some\class', ['aliases'], [/* default params */], true);

// aside from register and instance there is an invoke method
$di->invoke('\test\C', 'sum'); // returns 1

// you can also pass in arguments
$di->invoke('\test\C', 'sum', [2]); // returns 2

// and even constructor parameters
$di->invoke('\test\C', 'sum', [2], [5,6]);

// invoke works with instances too
$c1 = new C();
$di->invoke($c1, 'sum'); // returns 1


$ composer test


Please see CONTRIBUTING for details.


If you discover any security related issues, please email instead of using the issue tracker.



The MIT License (MIT). Please see License File for more information.