initphp/container 问题修复 & 功能扩展

解决BUG、新增功能、兼容多环境部署,快速响应你的开发需求

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

initphp/container

Composer 安装命令:

composer require initphp/container

包简介

Minimal PSR-11 dependency injection container with reflection-based autowiring.

README 文档

README

Minimal PSR-11 dependency injection container with reflection-based autowiring.

Latest Stable Version Total Downloads License PHP Version Require

The container resolves entries lazily. You can register values, factories and class bindings explicitly, or let the container autowire a class straight from its name by reading its constructor signature through reflection. Every resolved entry is cached, so the container behaves as a shared (singleton) registry.

Requirements

Installation

composer require initphp/container

Quick Start

require_once 'vendor/autoload.php';

use InitPHP\Container\Container;

class Mailer
{
}

class UserService
{
    public function __construct(public Mailer $mailer)
    {
    }
}

$container = new Container();

// No registration needed: the container reads UserService's constructor,
// builds the Mailer dependency automatically and injects it.
$service = $container->get(UserService::class);

var_dump($service instanceof UserService); // bool(true)
var_dump($service->mailer instanceof Mailer); // bool(true)

Usage

Autowiring

When you call get() with an existing class name, the container instantiates it and recursively resolves every class-typed constructor argument:

$service = $container->get(UserService::class);

The resolved instance is cached. Asking for the same identifier again returns the exact same object:

$container->get(Mailer::class) === $container->get(Mailer::class); // true

Storing values

set() accepts any value. Scalars, arrays and objects are returned as they were stored:

$container->set('app.name', 'InitPHP');
$container->set('config', ['debug' => true]);
$container->set('logger', new FileLogger('/var/log/app.log'));

$container->get('app.name'); // 'InitPHP'
$container->get('config');   // ['debug' => true]
$container->get('logger');   // the same FileLogger instance

Factories (closures)

Register a Closure to build an entry lazily. The closure receives the container and runs only once, the first time the entry is requested:

use Psr\Container\ContainerInterface;

$container->set('pdo', function (ContainerInterface $c) {
    return new PDO('sqlite::memory:');
});

$pdo = $container->get('pdo'); // closure runs here, result is cached

Binding interfaces to implementations

Bind an interface (or any identifier) to a concrete class name so that both direct lookups and autowired dependencies resolve to the implementation:

interface LoggerInterface
{
}

class FileLogger implements LoggerInterface
{
}

class Report
{
    public function __construct(public LoggerInterface $logger)
    {
    }
}

$container->set(LoggerInterface::class, FileLogger::class);

$container->get(LoggerInterface::class);      // FileLogger instance
$container->get(Report::class)->logger;       // the same FileLogger instance

Checking for an entry

has() returns true when get() would not throw a NotFoundException — that is, the identifier is a registered entry or an existing class name:

$container->has('app.name');         // true after set()
$container->has(UserService::class); // true (autowirable class)
$container->has('missing');          // false

How resolution works

get($id) resolves in this order:

  1. Return the cached instance if $id was resolved before.
  2. If $id was registered with set(), build it (invoke the closure, instantiate the class name, or return the stored value) and cache it.
  3. If $id is an existing class name, autowire it and cache it.
  4. Otherwise throw NotFoundException.

Constructor parameters are resolved as follows: a class-typed parameter is fetched from the container; otherwise its default value is used; otherwise null is supplied for nullable parameters. If none of these apply, resolution fails.

Exceptions

All exceptions live in InitPHP\Container\Exception and implement the relevant PSR-11 interface.

Exception Implements Thrown when
NotFoundException Psr\Container\NotFoundExceptionInterface The identifier is neither registered nor an existing class.
DependencyIsNotInstantiableException Psr\Container\ContainerExceptionInterface The target is an interface, abstract class, or has a non-public constructor.
DependencyHasNoDefaultValueException Psr\Container\ContainerExceptionInterface A constructor parameter cannot be autowired and has no default or nullable fallback.
CircularDependencyException Psr\Container\ContainerExceptionInterface A class depends on itself directly or through a cycle.

ContainerException is the base class for NotFoundException and the three resolution exceptions, so you can catch every container error with a single catch (ContainerException $e).

Documentation

In-depth guides with runnable examples live in the docs/ directory:

Testing

composer test      # PHPUnit
composer stan      # PHPStan (max level)
composer cs-check  # PHP-CS-Fixer (dry run)

Contributing

Contributions are welcome. Please read the org-wide CONTRIBUTING guide before opening a pull request.

Credits

License

Released under the MIT License.

initphp/container 适用场景与选型建议

initphp/container 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 108 次下载、GitHub Stars 达 1, 最近一次更新时间为 2022 年 04 月 25 日, 在 PHP 生态内属于活跃度较高的组件。

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

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

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

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

BUG 修复 & 性能优化

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

项目外包 & 长期维护

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

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

统计信息

  • 总下载量: 108
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 1
  • 点击次数: 8
  • 依赖项目数: 0
  • 推荐数: 0

GitHub 信息

  • Stars: 1
  • Watchers: 1
  • Forks: 0
  • 开发语言: PHP

其他信息

  • 授权协议: MIT
  • 更新时间: 2022-04-25