定制 sanmai/di-container 二次开发

按需修改功能、优化性能、对接业务系统,提供一站式技术支持

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

sanmai/di-container

Composer 安装命令:

composer require sanmai/di-container

包简介

dependency injection container with automatic constructor dependency resolution

README 文档

README

A straightforward PSR-11 dependency injection container with automatic constructor dependency resolution.

I designed the autowiring initially for Infection's own use with focus on simplicity and zero configuration, building on the existing implementation by Maks Rafalko and Théo Fidry.

Installation

composer require sanmai/di-container

Features

  • Automatically resolves class dependencies through reflection
  • Objects are created once and reused
  • Resolve interfaces to concrete implementations

Quick Start

use DIContainer\Container;

$container = new Container();

// Automatic resolution - no configuration needed
$service = $container->get(YourService::class);

// Use builder objects for complex construction, or construct the dependencies directly - your choice
$container = new Container([
    ComplexObject::class => fn(Container $container) => new ComplexObject(
        $container->get(LoggerInterface::class),
        $container->get(AnotherProvider::class)->getValue()
    ),
    DatabaseInterface::class => fn(Container $container) =>
        $container->get(DatabaseBuilder::class)->build(),
]);

// Set additional dependencies on the fly
$container->set(LoggerInterface::class, fn() => new FileLogger('debug.log'));

$service = $container->get(ServiceNeedingDatabase::class); // Auto-injects database

The order in which you define your services is not important, as dependencies are only resolved when they are requested.

That said, injected pre-built instance instances override prior dependencies for that ID, but a later set() or bind() overrides again.

Builder Objects

Builder objects can encapsulate arbitrary complex construction logic. They can use dependency injection, which makes them cohesive, independently testable, and reusable.

use DIContainer\Builder;

/**
 * Builder that accepts injectable dependencies.
 *
 * @implements Builder<DatabaseInterface>
 */
class DatabaseBuilder implements Builder
{
    public function __construct(
        private readonly ConfigProvider $config,
        private readonly Logger $logger
    ) {}

    public function build(): DatabaseInterface
    {
        return new MySQLDatabase(
            $this->config->getDatabaseHost(),
            $this->config->getDatabaseCredentials(),
            $this->logger
        );
    }
}

The Builder interface uses a covariant template (@template-covariant T), so PHPStan correctly validates that your builder's return type matches the declared template parameter.

When you implement the Builder interface, you can simply provide the builder class name instead of a closure. The container automatically detects builder classes and handles the instantiation and build() method call.

// 1. Direct class name, if the class implements DIContainer\Builder interface
$container = new Container([
    DatabaseInterface::class => DatabaseBuilder::class,
]);

// 2. Explicit closure - what will the container do under the hood
$container = new Container([
    DatabaseInterface::class => fn(Container $container) => $container->get(DatabaseBuilder::class)->build(),
]);

For setting dependencies on the fly, there's a handy set() method that accepts both callables and builders.

Non-Class Service IDs

For non-class service IDs (e.g., 'app.repository'), use the bind() method or the $bindings constructor parameter:

// Register with a dotted ID - type validation is skipped
$container = new Container(
    values: [
        LoggerInterface::class => FileLogger::class,
    ],
    bindings: [
        'app.repository' => fn() => new CachedRepository(new DatabaseRepository()),
        'app.cache' => CacheBuilder::class,
    ]
);

// Or add bindings on the fly
$container->bind('app.mailer', fn() => new MyMailer());

// Builder classes work too
$container->bind('app.session', SessionBuilder::class);

$repository = $container->get('app.repository');

The bind() method and $bindings parameter accept both callables and builder class names, just like set(), but without class-string type constraints on the service ID.

Pre-Built Instances

Use inject() to store objects that were created outside the container:

$logger = new FileLogger('app.log');
$container->inject(LoggerInterface::class, $logger);

Design Philosophy

This container prioritizes simplicity, predictability, and architectural purity. It achieves this through:

  • Predictable autowiring; there are no complex background scans or fragile naming conventions.
  • Lack of surprises; the container will only resolve an interface if it can find exactly one registered factory or builder that produces a compatible implementation. It will never guess, ensuring the dependency graph is always clear, just as your day is worry-free.
  • Constructor-only dependency injection; the container intentionally avoids complex features, such as property/method injection or injection of variadic/composite types beyond default values. This approach promotes cleaner, more testable class designs.

The container resolves interfaces using a straightforward rule: when a dependency is an interface, it looks for exactly one registered factory or a builder that produces a compatible object.

This approach allows you to wire dependencies without explicitly linking an implementation to an interface; the container connects them logically as long as the relationship is unambiguous.

The container omits circular dependency checks for simplicity, an issue that even the most minimal automatic test will immediately reveal.

Testing

make -j -k

Benchmarking

make benchmark

Runs PHPBench with OPcache and JIT enabled.

sanmai/di-container 适用场景与选型建议

sanmai/di-container 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 4.46M 次下载、GitHub Stars 达 7, 最近一次更新时间为 2025 年 07 月 23 日, 在 PHP 生态内属于活跃度较高的组件。

它主要适用于以下技术方向: 「di container」 「Autowiring」 「psr 11」 「constructor di」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。

我们在过去多个企业项目中使用过 sanmai/di-container 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。

围绕 sanmai/di-container 我们能提供哪些服务?
定制开发 / 二次开发

基于 sanmai/di-container 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。

BUG 修复 & 性能优化

线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。

项目外包 & 长期维护

承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。

yvsm@zunyunkeji.com QQ:316430983 微信:yvsm316 西安尊云信息科技 · 专注 PHP / Go / 分布式系统研发

统计信息

  • 总下载量: 4.46M
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 7
  • 点击次数: 33
  • 依赖项目数: 1
  • 推荐数: 0

GitHub 信息

  • Stars: 7
  • Watchers: 1
  • Forks: 2
  • 开发语言: PHP

其他信息

  • 授权协议: BSD-3-Clause
  • 更新时间: 2025-07-23