PHPackages                             michel/psr11-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. michel/psr11-di

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

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.

1.0.0(8mo ago)05MITPHPPHP &gt;=7.4

Since Dec 15Pushed 8mo agoCompare

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

READMEChangelog (1)Dependencies (2)Versions (2)Used By (0)

PSR-11 Dependency Injection Container
=====================================

[](#psr-11-dependency-injection-container)

[English](#english) | [Français](#fran%C3%A7ais)

---

English
-------

[](#english)

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

### Features

[](#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

[](#installation)

```
composer require michel/psr11-di
```

### Usage

[](#usage)

#### 1. Basic Usage (ContainerBuilder)

[](#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

[](#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)

[](#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

[](#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
-----------

[](#-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

[](#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

[](#installation-1)

```
composer require michel/psr11-di
```

### Utilisation

[](#utilisation)

#### 1. Utilisation de base (ContainerBuilder)

[](#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)

[](#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)

[](#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

[](#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
-------

[](#license)

MIT License.

###  Health Score

28

—

LowBetter than 51% of packages

Maintenance61

Regular maintenance activity

Popularity4

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity35

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.

###  Release Activity

Cadence

Unknown

Total

1

Last Release

245d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/909a078010ad44ff35146af8288451a3b6fd26f81cb198cbea776a92553c9b8a?d=identicon)[F.Michel](/maintainers/F.Michel)

---

Top Contributors

[![michelphp](https://avatars.githubusercontent.com/u/26349908?v=4)](https://github.com/michelphp "michelphp (1 commits)")

### Embed Badge

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

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

###  Alternatives

[symfony/symfony

The Symfony PHP framework

31.4k87.4M2.2k](/packages/symfony-symfony)[symfony/dependency-injection

Allows you to standardize and centralize the way objects are constructed in your application

4.2k464.3M10.6k](/packages/symfony-dependency-injection)[api-platform/core

Build a fully-featured hypermedia or GraphQL API in minutes!

2.6k52.2M377](/packages/api-platform-core)[tempest/framework

The PHP framework that gets out of your way.

2.3k37.6k21](/packages/tempest-framework)[ecotone/ecotone

Enterprise architecture layer for Laravel and Symfony — CQRS, Event Sourcing, Durable Workflows (Sagas, Orchestrators), Projections, and Outbox messaging via PHP attributes.

568591.1k63](/packages/ecotone-ecotone)[api-platform/state

API Platform state interfaces

275.4M157](/packages/api-platform-state)

PHPackages © 2026

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