Lightweight PSR-11 dependency injection container for PHP 8.1+
Лёгкий DI-контейнер: autowiring, конфигурация PHP/JSON/YAML/XML, scan, теги, декораторы.
⚡ Quick start · 📊 Сравнение · 📚 Wiki · Packagist · Releases
English: Lightweight PSR-11 dependency injection container for PHP 8.1+. Explicit set() / get() wiring, optional constructor/property/method autowiring, declarative configuration (PHP/JSON/YAML/XML), directory scan, prototypes (make), aliases, lazy services, callable invocation (call), interface binding (bind), after-resolving hooks, custom inject attributes, tagged services (ids / iterator / locator), decorators, global registry — one runtime dependency (psr/container).
Русский: Лёгкий контейнер внедрения зависимостей для PHP 8.1+ с поддержкой PSR-11. Явная регистрация сервисов, singleton-фабрики, autowiring конструктора, свойств и методов, конфигурация из файлов, сканирование каталогов, прототипы, alias, lazy, вызов callable с autowire, bind, afterResolving, пользовательские attributes, теги, декораторы и глобальный реестр.
| CloudCastle DI | PHP-DI | Symfony DI | Pimple | Laravel | Nette DI | |
|---|---|---|---|---|---|---|
| Runtime deps | 1 | неск. | symfony/* | 0 | illuminate/* | nette/* |
| Autowiring | ✅ | ✅ | ✅ | ❌ | ✅ | ✅ |
| Compiled / contextual | ✅ compiled (v1.9) + contextual (v1.10–1.13) | ✅ | ✅ | ❌ | ✅ | ✅ |
| Конфиг YAML/JSON | ✅ | ✅ | ✅ | ❌ | ✅ | ✅ NEON |
Полная таблица (5 аналогов, колонка 🏆 победитель): Wiki: Comparison
| ✅ Подходит | ❌ Лучше другой |
|---|---|
| Composition root, CLI, API, библиотеки | Уже Symfony / Laravel / Nette |
| Autowiring + compiled + contextual без фреймворка | Legacy PHP < 8.1 |
Одна зависимость psr/container |
3–5 set() без autowire → Pimple |
Базовый DI · Autowiring · Scan · Config · Tags
| Категория | Возможности |
|---|---|
| Базовый DI | set() / get() / has(), фабрики, singleton-кэш, PSR-11 |
| Autowiring | constructor, property, method; Inject / Autowire; union, intersection |
| Scan | scan() — обход каталога, фильтр namespace |
| Конфиг | ContainerConfigurator — PHP, JSON, YAML, XML; priority; каталоги (v1.7) |
| Расширения | make(), alias(), lazy(), lazyGhost() (v1.18), call(), bind(), afterResolving() |
| Теги | tag(), iterator, locator, decorate() |
| Прочее | freeze(), dump(), ContainerRegistry |
| Compiled (v1.9) | ContainerCompiler — PHP-класс без reflection на hot path |
| Contextual (v1.10–1.13) | when()->needs()->give() — runtime, config, compiled (#25) |
| Observability (opt-in) | profiler (v1.15), memory pool (v1.16), smart cache TTL (v1.17) — см. Performance |
flowchart TB
subgraph entry [Точки входа]
GET["get() — singleton"]
MAKE["make() — прототип"]
CALL["call() — autowire callable"]
end
subgraph bootstrap [Bootstrap]
REG_API["set / bind / autowire / scan"]
CONFIG["ContainerConfigurator"]
FREEZE["freeze()"]
end
subgraph container [Container]
RESOLVE[ServiceInstanceResolver]
AUTO[Autowirer]
DECO[decorators]
TAGS[tags]
end
REG_API --> RESOLVE
CONFIG --> REG_API
GET --> RESOLVE
MAKE --> RESOLVE
CALL --> AUTO
RESOLVE --> AUTO
RESOLVE --> DECO
FREEZE -.->|блокирует| REG_API
Схемы всех потоков — Wiki: Архитектура.
- PHP ^8.1 (CI: 8.1–8.5)
psr/container^2.0- Опционально:
ext-yaml— YAML-конфигурация
composer require cloudcastle/di:^1.18<?php
use CloudCastle\DI\Container;
$container = new Container();
$container->enableAutowiring();
$container->bind(LoggerInterface::class, FileLogger::class);
$service = $container->get(App\Service\UserService::class);Больше примеров — Wiki: Quick start · Bootstrap.
Примеры: явная регистрация, autowiring, scan, теги, конфиг
$container = new Container();
$container->set('logger', new Psr\Log\NullLogger());
$container->set(
'repository',
static fn (Container $c) => new UserRepository($c->get('logger')),
);$container->enableAutowiring();
$container->enableParameterNameAutowiring();
$userService = $container->get(App\Service\UserService::class);$container->scan(__DIR__ . '/Services', 'App\\Services\\');
$container->bind(LoggerInterface::class, FileLogger::class);
$container->call(static fn (LoggerInterface $log) => $log->info('ok'));
$container->tag('handler.email', 'handlers');use CloudCastle\DI\Configuration\ContainerConfigurator;
(new ContainerConfigurator())->configure($container, [
__DIR__ . '/config/services.php',
]);
$container->freeze();| Раздел | Ссылка |
|---|---|
| 📚 Wiki — главная | Home |
| 📊 Сравнение (таблица) | Comparison |
| ⚡ Быстрый старт | Quick-start |
| 🏗️ Архитектура | Architecture |
| 📄 Конфигурация | Configuration |
| 📖 Справочник конфига | Configuration-reference |
| 📋 API | API-reference |
| 🚀 Compiled container | Compiled-container |
| 🔗 Contextual binding | Contextual-binding |
Исходники Wiki — каталог wiki/. API после composer docs → docs/.
composer install
composer ci| Тесты | 744 PHPUnit (unit 689, integration 11, security 17, load 15, performance 12) |
| Статика | PHPStan max, Psalm 6 (errorLevel 1), PHPMD, Deptrac, Rector |
| Coverage | ≥95% line (per-file), ~99.8% типично; Infection MSI ≥94% |
| CI | PHP 8.1–8.5, benchmark-check, CodeQL |
Wiki: Testing · Performance-and-load
- Discussions — вопросы и идеи
- Issues — баги и задачи