PHPackages                             inilim/di - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Framework](/categories/framework)
4. /
5. inilim/di

ActiveLibrary[Framework](/categories/framework)

inilim/di
=========

end-to-end dependency injection

029PHP

Since Mar 24Pushed 1mo ago1 watchersCompare

[ Source](https://github.com/inilim/di)[ Packagist](https://packagist.org/packages/inilim/di)[ RSS](/packages/inilim-di/feed)WikiDiscussions main Synced 1mo ago

READMEChangelogDependenciesVersions (1)Used By (0)

\[EN\] DI (Dependency Injection) Library
========================================

[](#en-di-dependency-injection-library)

This library provides a powerful and flexible dependency injection system for PHP applications. It allows easy management of dependencies, creates objects with automatic dependency injection, and configures different implementations for contracts and interfaces.

Features
--------

[](#features)

- **Simple dependency injection**: Automatic object creation with dependency injection
- **Context support**: Ability to configure different implementations based on context
- **Tag support**: Using tags for dependency identification
- **Singletons**: Singleton creation support to save resources
- **Swap functionality**: Ability to replace implementations at runtime
- **Flexible configuration**: Closure support for complex object creation logic

Installation
------------

[](#installation)

```
composer require inilim/di:dev-main
```

Quick Start
-----------

[](#quick-start)

```
use Inilim\DI\DI;

// Object creation
$obj = \DI(MyClass::class);

// Object creation with arguments
$obj = \DI(MyClass::class, ['arg1', 'arg2']);

// Object creation with context
$obj = \DI(MyClass::class, null, MyContext::class);
```

Dependency Binding
------------------

[](#dependency-binding)

```
use Inilim\DI\Bind;

$bind = Bind::self();

// Simple interface to implementation binding
$bind->class(Interface::class, Implementation::class);

// Singleton binding
$bind->singleton(Service::class);

// Binding using closure
$bind->class(Service::class, function($di, $args) {
    return new Service($di->DI(Dependency::class));
});

// Binding with context
$bind->class(Interface::class, ImplementationA::class, ContextA::class);
$bind->class(Interface::class, ImplementationB::class, ContextB::class);

// Conditional binding (doesn't overwrite existing)
$bind->classIf(Interface::class, FallbackImplementation::class);

// Tag-based binding
$bind->classTag('my_tag', MyService::class);

// Conditional tag-based binding
$bind->classTagIf('optional_tag', OptionalService::class);

// Registering a list of singletons
$bind->singletonList([
    ServiceA::class,
    ServiceB::class,
    ServiceC::class
]);

// Conditional singleton registration
$bind->singletonIf(ConfigService::class, ConfigService::class);

// Singleton registration by tag
$bind->singletonTag('db_connection', DatabaseConnection::class);

// Conditional singleton registration by tag
$bind->singletonTagIf('cache', CacheService::class);
```

Using Tags
----------

[](#using-tags)

```
// Tag-based binding
$bind->classTag('logger', FileLogger::class);

// Getting object by tag
$logger = \DITag('logger');
```

Singletons
----------

[](#singletons)

```
// Singleton registration
$bind->singleton(DatabaseConnection::class);

// All calls will return the same instance
$conn1 = \DI(DatabaseConnection::class);
$conn2 = \DI(DatabaseConnection::class);
$conn1 === $conn2 // true
```

Implementation Swapping (Swap)
------------------------------

[](#implementation-swapping-swap)

```
// Implementation replacement
$bind->swap(OriginalClass::class, MockClass::class);

// Tag-based replacement
$bind->swapTag('original_tag', 'mock_tag');
```

Testing with Mocks and Swaps
----------------------------

[](#testing-with-mocks-and-swaps)

When writing PHPUnit tests, you can use the swap functionality to replace real implementations with mocks:

```
use PHPUnit\Framework\TestCase;
use Inilim\DI\Bind;

class MyServiceTest extends TestCase
{
    public function testServiceWithMockDependency()
    {
        // Create a mock for the dependency
        $mockDependency = $this->createMock(DependencyInterface::class);
        $mockDependency->method('someMethod')
                       ->willReturn('mocked result');

        // Swap the real dependency with the mock
        $bind = Bind::self();
        $bind->swap(DependencyInterface::class, $mockDependency);

        // Now when we create our service, it will use the mock
        $service = \DI(MyService::class);

        // Perform your test
        $result = $service->doSomething();

        // Assertions
        $this->assertEquals('expected result', $result);
    }
}
```

Contextual Dependency
---------------------

[](#contextual-dependency)

The library supports contextual dependency, allowing different implementations of the same interface based on the application context.

```
// Different implementations for different contexts
$bind->class(RepositoryInterface::class, UserRepository::class, UserController::class);
$bind->class(RepositoryInterface::class, OrderRepository::class, OrderController::class);
```

Requirements
------------

[](#requirements)

- PHP &gt;= 7.4

License
-------

[](#license)

MIT License

\[RU\] DI (Dependency Injection) Library
========================================

[](#ru-di-dependency-injection-library)

Эта библиотека предоставляет мощную и гибкую систему внедрения зависимостей (Dependency Injection) для PHP-приложений. Она позволяет легко управлять зависимостями, создавать объекты с автоматическим внедрением зависимостей и настраивать различные реализации для контрактов и интерфейсов.

Особенности
-----------

[](#особенности)

- **Простое внедрение зависимостей**: Автоматическое создание объектов с внедрением зависимостей
- **Поддержка контекстов**: Возможность настройки различных реализаций в зависимости от контекста
- **Поддержка тегов**: Использование тегов для идентификации зависимостей
- **Синглтоны**: Поддержка создания синглтонов для экономии ресурсов
- **Swap-функциональность**: Возможность замены реализаций в runtime
- **Гибкая конфигурация**: Поддержка замыканий для сложной логики создания объектов

Установка
---------

[](#установка)

```
composer require inilim/di:dev-main
```

Быстрый старт
-------------

[](#быстрый-старт)

```
// Создание объекта
$obj = \DI(MyClass::class);

// Создание объекта с аргументами
$obj = \DI(MyClass::class, ['arg1', 'arg2']);

// Создание объекта с контекстом
$obj = \DI(MyClass::class, null, MyContext::class);
```

Привязка зависимостей
---------------------

[](#привязка-зависимостей)

```
use Inilim\DI\Bind;

$bind = Bind::self();

// Простая привязка интерфейса к реализации
$bind->class(Interface::class, Implementation::class);

// Привязка синглтона
$bind->singleton(Service::class);

// Привязка с использованием замыкания
$bind->class(Service::class, function($di, $args) {
    return new Service($di->DI(Dependency::class));
});

// Привязка с контекстом
$bind->class(Interface::class, ImplementationA::class, ContextA::class);
$bind->class(Interface::class, ImplementationB::class, ContextB::class);

// Условная привязка (не перезаписывает существующую)
$bind->classIf(Interface::class, FallbackImplementation::class);

// Привязка по тегу
$bind->classTag('my_tag', MyService::class);

// Условная привязка по тегу
$bind->classTagIf('optional_tag', OptionalService::class);

// Регистрация списка синглтонов
$bind->singletonList([
    ServiceA::class,
    ServiceB::class,
    ServiceC::class
]);

// Условная регистрация синглтона
$bind->singletonIf(ConfigService::class, ConfigService::class);

// Регистрация синглтона по тегу
$bind->singletonTag('db_connection', DatabaseConnection::class);

// Условная регистрация синглтона по тегу
$bind->singletonTagIf('cache', CacheService::class);
```

Использование тегов
-------------------

[](#использование-тегов)

```
// Привязка по тегу
$bind->classTag('logger', FileLogger::class);

// Получение объекта по тегу
$logger = \DITag('logger');
```

Синглтоны
---------

[](#синглтоны)

```
// Регистрация синглтона
$bind->singleton(DatabaseConnection::class);

// Все вызовы будут возвращать один и тот же экземпляр
$conn1 = \DI(DatabaseConnection::class);
$conn2 = \DI(DatabaseConnection::class);
$conn1 === $conn2 // true
```

Замена реализаций (Swap)
------------------------

[](#замена-реализаций-swap)

```
// Замена реализации
$bind->swap(OriginalClass::class, MockClass::class);

// Замена по тегу
$bind->swapTag('original_tag', 'mock_tag');
```

Контекстная зависимость
-----------------------

[](#контекстная-зависимость)

Библиотека поддерживает контекстную зависимость, что позволяет использовать разные реализации одного и того же интерфейса в зависимости от контекста приложения.

```
// Разные реализации для разных контекстов
$bind->class(RepositoryInterface::class, UserRepository::class, UserController::class);
$bind->class(RepositoryInterface::class, OrderRepository::class, OrderController::class);
```

Требования
----------

[](#требования)

- PHP &gt;= 7.4

License
-------

[](#license-1)

MIT License

###  Health Score

22

—

LowBetter than 22% of packages

Maintenance59

Moderate activity, may be stable

Popularity8

Limited adoption so far

Community7

Small or concentrated contributor base

Maturity11

Early-stage or recently created project

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

### Community

Maintainers

![](https://www.gravatar.com/avatar/621e962a960c28d148de832ecc102b87dd0ca07d3ceb3360bbdf0211dff56c62?d=identicon)[inilim](/maintainers/inilim)

---

Top Contributors

[![inilim](https://avatars.githubusercontent.com/u/40324321?v=4)](https://github.com/inilim "inilim (66 commits)")

### Embed Badge

![Health badge](/badges/inilim-di/health.svg)

```
[![Health](https://phpackages.com/badges/inilim-di/health.svg)](https://phpackages.com/packages/inilim-di)
```

###  Alternatives

[laravel/telescope

An elegant debug assistant for the Laravel framework.

5.2k67.8M192](/packages/laravel-telescope)[spiral/roadrunner

RoadRunner: High-performance PHP application server and process manager written in Go and powered with plugins

8.4k12.2M84](/packages/spiral-roadrunner)[nolimits4web/swiper

Most modern mobile touch slider and framework with hardware accelerated transitions

41.8k177.2k1](/packages/nolimits4web-swiper)[laravel/dusk

Laravel Dusk provides simple end-to-end testing and browser automation.

1.9k36.7M259](/packages/laravel-dusk)[laravel/prompts

Add beautiful and user-friendly forms to your command-line applications.

708181.8M596](/packages/laravel-prompts)[cakephp/chronos

A simple API extension for DateTime.

1.4k47.7M121](/packages/cakephp-chronos)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
