Skip to content

Compilable definition decorators via addDecorator() #294

@philipobenito

Description

@philipobenito

Summary

Add addDecorator(string $decoratorClass) to DefinitionInterface for compile-time decorator chain support.

Context

The event system (afterResolve() and ServiceResolvedEvent) already supports runtime decoration, but event listeners do not survive compilation. This feature would allow decorator chains to be expressed declaratively on definitions and compiled into nested constructor calls:

$container->add(CacheInterface::class, RedisCache::class)
    ->addDecorator(LoggingCacheDecorator::class)
    ->addDecorator(MetricsCacheDecorator::class);

The compiled output would emit:

private function createCacheInterface(): mixed
{
    return new MetricsCacheDecorator(
        new LoggingCacheDecorator(
            new RedisCache()
        )
    );
}

Implementation notes

  • Definition stores an ordered list of decorator classes
  • At runtime, Definition::resolve() resolves the base service then wraps through the decorator chain, resolving each decorator via the container with the previous result injected
  • For shared services, the decorated result is cached (not the base)
  • DefinitionAnalyser reads decorator metadata and CodeGenerator emits nested instantiation
  • Decorators on delegate-resolved services (no definition) remain event-only, which is an acceptable limitation
  • Event interplay: definition-level decorators apply first, then ServiceResolvedEvent listeners fire on the already-decorated instance

Target

6.1+ minor release

Metadata

Metadata

Assignees

No one assigned

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions