Skip to content

Contextual binding

github-actions[bot] edited this page Jun 28, 2026 · 1 revision

CloudCastle DI

🔗 Contextual binding (#25)

← Главная · API · Compiled container

Contextual binding — привязка зависимости к контексту класса-потребителя: when(A)->needs(B)->give(C).

Аналог Laravel when()->needs()->give() и PHP-DI contextual definitions.


Статус (v1.13.0)

Этап Статус MR / релиз
1. Контракты ✅ v1.10.0 #61
2. Runtime ✅ v1.11.0 Container::when(), registry, autowirer
3. Config ✅ v1.12.0 секция contextual в PHP/JSON/YAML/XML
4. Compiler ✅ v1.13.0 compile snapshot + contextualGive()

Runtime, config и compiled container поддерживают contextual binding (#25 завершён).

Пример (runtime)

$container->enableAutowiring();
$container->bind(LoggerInterface::class, 'default.logger');
$container->set('memory.logger', new MemoryLogger());
$container->when(ReportService::class)
    ->needs(LoggerInterface::class)
    ->give('memory.logger');

$report = $container->get(ReportService::class); // MemoryLogger
$other = $container->get(AuditService::class);   // default binding

Пример (config, v1.12.0)

contextual:
  App\ReportService:
    Psr\Log\LoggerInterface: memory.logger
(new ContainerConfigurator())->configure($container, [__DIR__ . '/container.yaml']);

Контракты (v1.10.0) и runtime (v1.11.0)

ContextualBinding

Value object: consumerClass (when), need (needs), give (id или FQCN).

Fluent API (интерфейсы)

$container->when(ReportController::class)
    ->needs(LoggerInterface::class)
    ->give(FileLogger::class);
Интерфейс Метод
ContextualBindingConfiguratorInterface when(string $consumerClass)
ContextualBindingNeedsInterface needs(string $need)
ContextualBindingGiveInterface give(string $serviceId)

ContextualBindingRegistryInterface

Метод Описание
register(ContextualBinding $binding) Добавить правило
bindingsFor(string $consumerClass) Список правил для класса
resolve(string $consumerClass, string $need) id для give или null

Roadmap


См. также

Clone this wiki locally