Skip to content

Add #[When] attribute for contextual binding via attributes #291

Description

@philipobenito

Summary

Add a #[When(ConsumerClass::class)] parameter-level attribute as the attribute-surface counterpart to addContextualArgument().

This allows contextual binding to be declared at the class level rather than in the container bootstrap:

class FileCache implements CacheInterface {}

class LogService
{
    public function __construct(
        #[When(LogService::class)] CacheInterface $cache
    ) {}
}

Context

Contextual binding was introduced in 6.0 via addContextualArgument() on definitions. The #[When] attribute would provide the same capability through PHP attributes, consistent with the existing #[Inject] and #[Resolve] attributes.

The committee recommended deferring this to 6.1 to let the core contextual binding API settle before adding the attribute form.

Implementation notes

  • Parameter-level attribute following the #[Inject]/#[Resolve] pattern
  • May need a new interface (e.g. ContextualAttributeInterface) since #[When] declares a binding rule rather than directly resolving a value
  • DefinitionAnalyser already handles attribute resolution during autowiring (lines 222-239 of DefinitionAnalyser.php), so compilation support is achievable
  • The ArgumentReflectorTrait::resolveArgumentFromAttribute() method would need to handle the new attribute type

Target

6.1 minor release

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions