定制 michel/psr11-di 二次开发

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

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

michel/psr11-di

Composer 安装命令:

composer require michel/psr11-di

包简介

A lightweight PHP Dependency Injection Container implementing the PSR-11 standard. This library is designed for simplicity and ease of use, making it an ideal choice for small projects where you need a quick and effective DI solution.

README 文档

README

English | Français

English

A lightweight PHP Dependency Injection Container implementing the PSR-11 standard. This library is designed for simplicity, performance, and ease of use.

Features

  • PSR-11 Compliant: Interoperable with other libraries.
  • Autowiring: Automatically resolves dependencies using Reflection.
  • Compilation/Caching: Compiles definitions to plain PHP for zero-overhead production performance.
  • Parameter Resolution: Supports #{variable} syntax in strings.

Installation

composer require michel/psr11-di

Usage

1. Basic Usage (ContainerBuilder)

The ContainerBuilder is the recommended way to create your container.

use Michel\DependencyInjection\ContainerBuilder;

$builder = new ContainerBuilder();

// Add definitions
$builder->addDefinitions([
    'database.host' => 'localhost',
    'database.name' => 'app_db',
    PDO::class => function ($c) {
        return new PDO(
            "mysql:host={$c->get('database.host')};dbname={$c->get('database.name')}",
            "root",
            ""
        );
    }
]);

$container = $builder->build();

$pdo = $container->get(PDO::class);

2. Autowiring

You don't need to define every class manually. If a class exists, the container will try to instantiate it and inject its dependencies automatically.

class Mailer {
    // ...
}

class UserManager {
    public function __construct(Mailer $mailer) {
        $this->mailer = $mailer;
    }
}

// No definitions needed!
$container = (new ContainerBuilder())->build();

$userManager = $container->get(UserManager::class);

3. Production Performance (Caching)

In production, using Reflection for every request is slow. You can enable compilation to generate a PHP file containing all your definitions and resolved dependencies.

How it works:

  1. The first time, it inspects your code and generates a PHP file.
  2. Subsequent requests load this file directly, bypassing Reflection entirely.
$builder = new ContainerBuilder();
$builder->addDefinitions([/* ... */]);

// Enable compilation
// Ideally, do this only in production or when the cache file doesn't exist
$builder->enableCompilation(__DIR__ . '/var/cache/container.php');

$container = $builder->build();

Note: The compiler recursively discovers and compiles all dependencies for "total" resolution caching.

4. Variable Replacement

You can use placeholders in your string definitions.

$builder->addDefinitions([
    'app.path' => '/var/www/html',
    'app.log_file' => '#{app.path}/var/log/app.log',
]);

🇫🇷 Français

Un conteneur d'injection de dépendances PHP léger implémentant le standard PSR-11. Cette bibliothèque est conçue pour la simplicité, la performance et la facilité d'utilisation.

Fonctionnalités

  • Compatible PSR-11 : Interopérable avec d'autres bibliothèques.
  • Autowiring : Résout automatiquement les dépendances via la Réflexion.
  • Compilation/Cache : Compile les définitions en PHP pur pour des performances maximales en production.
  • Résolution de paramètres : Supporte la syntaxe #{variable} dans les chaînes.

Installation

composer require michel/psr11-di

Utilisation

1. Utilisation de base (ContainerBuilder)

Le ContainerBuilder est la méthode recommandée pour créer votre conteneur.

use Michel\DependencyInjection\ContainerBuilder;

$builder = new ContainerBuilder();

// Ajouter des définitions
$builder->addDefinitions([
    'database.host' => 'localhost',
    'database.name' => 'app_db',
    PDO::class => function ($c) {
        return new PDO(
            "mysql:host={$c->get('database.host')};dbname={$c->get('database.name')}",
            "root",
            ""
        );
    }
]);

$container = $builder->build();

$pdo = $container->get(PDO::class);

2. Autowiring (Injection Automatique)

Vous n'avez pas besoin de définir chaque classe manuellement. Si une classe existe, le conteneur essaiera de l'instancier et d'injecter ses dépendances automatiquement.

class Mailer {
    // ...
}

class UserManager {
    public function __construct(Mailer $mailer) {
        $this->mailer = $mailer;
    }
}

// Aucune définition nécessaire !
$container = (new ContainerBuilder())->build();

$userManager = $container->get(UserManager::class);

3. Performance en Production (Cache)

En production, utiliser la Réflexion à chaque requête est lent. Vous pouvez activer la compilation pour générer un fichier PHP contenant toutes vos définitions et dépendances résolues.

Comment ça marche :

  1. La première fois, il inspecte votre code et génère un fichier PHP.
  2. Les requêtes suivantes chargent directement ce fichier, contournant totalement la Réflexion.
$builder = new ContainerBuilder();
$builder->addDefinitions([/* ... */]);

// Activer la compilation
// Idéalement, faites ceci uniquement en production
$builder->enableCompilation(__DIR__ . '/var/cache/container.php');

$container = $builder->build();

Note : Le compilateur découvre et compile récursivement toutes les dépendances pour une mise en cache "totale" de la résolution.

4. Remplacement de variables

Vous pouvez utiliser des espaces réservés dans vos définitions de chaînes.

$builder->addDefinitions([
    'app.path' => '/var/www/html',
    'app.log_file' => '#{app.path}/var/log/app.log',
]);

License

MIT License.

michel/psr11-di 适用场景与选型建议

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

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

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

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

BUG 修复 & 性能优化

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

项目外包 & 长期维护

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

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

统计信息

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

GitHub 信息

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

其他信息

  • 授权协议: MIT
  • 更新时间: 2025-12-15