PHPackages                             kode/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. [PSR &amp; Standards](/categories/psr-standards)
4. /
5. kode/di

ActiveLibrary[PSR &amp; Standards](/categories/psr-standards)

kode/di
=======

高性能 PHP 8.1+ 依赖注入容器，支持属性注入、生命周期管理、协程上下文隔离，兼容 PSR-11

v1.0.3(3mo ago)00Apache-2.0PHPPHP ^8.1

Since Mar 14Pushed 3mo agoCompare

[ Source](https://github.com/kodephp/di)[ Packagist](https://packagist.org/packages/kode/di)[ Docs](https://github.com/kodephp/di)[ RSS](/packages/kode-di/feed)WikiDiscussions main Synced 3w ago

READMEChangelogDependencies (4)Versions (3)Used By (0)

kode/di
=======

[](#kodedi)

[![PHP Version](https://camo.githubusercontent.com/fabeba9a1fce5ab2d034002842f688c3a48beacc3845d75e287216c7c38e37e2/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f5048502d253345253344382e312d383839324246)](https://php.net/)[![License](https://camo.githubusercontent.com/109222cb0d1f59ed2e77b56722653623fa45f93e2bb201a6eef8561d26a52185/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f4c6963656e73652d417061636865253230322e302d677265656e2e737667)](LICENSE)[![PSR-11](https://camo.githubusercontent.com/0ca08488a1bdbd72bba9b210a1d6db78e3c49a450a3953760fafb7581b9ca83d/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f5053522d31312d436f6d70617469626c652d626c7565)](https://www.php-fig.org/psr/psr-11/)

高性能 PHP 8.1+ 依赖注入容器，支持属性注入、生命周期管理、协程上下文隔离，兼容 PSR-11。

特性
--

[](#特性)

- **PSR-11 兼容** - 实现标准容器接口
- **属性注入** - 基于 PHP 8.1+ Attributes 实现声明式注入
- **生命周期管理** - 单例/原型/懒加载/上下文隔离
- **协程安全** - 支持 Fiber/Swoole/Swow 上下文隔离
- **高性能** - 反射缓存 + 定义缓存
- **零全局状态** - 无全局变量污染
- **框架无关** - 可在任何 PHP 8.1+ 项目中使用

安装
--

[](#安装)

```
composer require kode/di
```

快速开始
----

[](#快速开始)

### 基本使用

[](#基本使用)

```
use Kode\DI\Container;

$container = new Container();

// 绑定单例
$container->singleton(LoggerInterface::class, FileLogger::class);

// 绑定原型
$container->prototype(Request::class);

// 获取实例
$logger = $container->get(LoggerInterface::class);
```

### 属性注入

[](#属性注入)

```
use Kode\DI\Attributes\Inject;
use Kode\DI\Attributes\Singleton;

#[Singleton]
class UserService
{
    #[Inject]
    private LoggerInterface $logger;

    #[Inject(id: 'cache.ttl', required: false)]
    private int $cacheTtl = 3600;
}
```

### 生命周期类型

[](#生命周期类型)

类型方法说明单例`singleton()`全局唯一实例原型`prototype()`每次获取创建新实例懒加载`lazy()`延迟实例化上下文隔离`contextual()`协程/Fiber间隔离### 上下文隔离

[](#上下文隔离)

```
use Kode\DI\ContextualContainer;

// 在协程环境中自动隔离实例
ContextualContainer::setContainer($container);

// 每个协程拥有独立实例
ContextualContainer::resolve(DatabaseConnection::class);
```

### 服务提供者

[](#服务提供者)

```
use Kode\DI\ServiceProvider;

class DatabaseServiceProvider extends ServiceProvider
{
    public function register(): void
    {
        $this->singleton(DatabaseInterface::class, MySQLDatabase::class);
    }

    public function boot(): void
    {
        // 启动逻辑
    }
}
```

### 上下文绑定

[](#上下文绑定)

```
// 当 UserController 需要 LoggerInterface 时，使用专门的实现
$container->when(UserController::class)
    ->needs(LoggerInterface::class)
    ->give(UserLogger::class);

// 使用闭包
$container->when(OrderController::class)
    ->needs(LoggerInterface::class)
    ->give(fn($c) => new OrderLogger('order.log'));
```

### 标签

[](#标签)

```
// 给服务打标签
$container->singleton(CacheInterface::class, RedisCache::class)->tag('cache');
$container->singleton(SessionInterface::class, RedisSession::class)->tag('cache');

// 获取所有带标签的服务
$cacheServices = $container->tagged('cache');
```

API 参考
------

[](#api-参考)

### Container

[](#container)

方法说明`bind(id, concrete, lifecycle)`绑定服务`singleton(id, concrete)`绑定单例`prototype(id, concrete)`绑定原型`lazy(id, concrete)`绑定懒加载`contextual(id, concrete)`绑定上下文隔离`instance(id, instance)`绑定实例`alias(alias, id)`设置别名`extend(id, callback)`扩展服务`get(id)`获取服务`has(id)`检查服务是否存在`make(id, parameters)`创建实例`call(callback, parameters)`调用方法`resolved(id)`检查是否已解析`forget(id)`移除绑定`flush()`清空容器### Attributes

[](#attributes)

属性目标说明`#[Inject]`Property, Parameter标记注入点`#[Autowire]`Class, Property, Method启用自动装配`#[Singleton]`Class标记为单例`#[Prototype]`Class标记为原型`#[Contextual]`Class标记为上下文隔离与其他 kode 组件集成
-------------

[](#与其他-kode-组件集成)

```
use Kode\DI\Container;
use Kode\Attributes\Attr;
use Kode\Context\Context;

// 自动使用 kode/attributes 进行属性读取
// 可选使用 kode/context 进行协程上下文隔离
```

兼容性
---

[](#兼容性)

PHP 版本支持状态PHP 8.1✅ 完全支持PHP 8.2✅ 完全支持PHP 8.3✅ 完全支持PHP 8.4✅ 完全支持PHP 8.5✅ 完全支持框架兼容性Laravel✅ 完全兼容Symfony✅ 完全兼容ThinkPHP 8✅ 完全兼容Webman✅ 完全兼容Hyperf✅ 完全兼容原生 PHP✅ 完全兼容测试
--

[](#测试)

```
composer test
```

许可证
---

[](#许可证)

[Apache License 2.0](LICENSE)

###  Health Score

35

—

LowBetter than 77% of packages

Maintenance82

Actively maintained with recent releases

Popularity0

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity44

Maturing project, gaining track record

 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.

###  Release Activity

Cadence

Every ~8 days

Total

2

Last Release

92d ago

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/230488886?v=4)[kodephp](/maintainers/kodephp)[@kodephp](https://github.com/kodephp)

---

Top Contributors

[![mofeier](https://avatars.githubusercontent.com/u/16829186?v=4)](https://github.com/mofeier "mofeier (7 commits)")

---

Tags

containerPSR-11dependency-injectiondiioccoroutineattributefiberkodephp

###  Code Quality

TestsPHPUnit

Static AnalysisPHPStan

Type Coverage Yes

### Embed Badge

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

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

###  Alternatives

[php-di/php-di

The dependency injection container for humans

2.8k53.2M1.2k](/packages/php-di-php-di)[slince/di

A flexible dependency injection container

20268.4k6](/packages/slince-di)

PHPackages © 2026

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