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
Summary
Add a
#[When(ConsumerClass::class)]parameter-level attribute as the attribute-surface counterpart toaddContextualArgument().This allows contextual binding to be declared at the class level rather than in the container bootstrap:
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
#[Inject]/#[Resolve]patternContextualAttributeInterface) since#[When]declares a binding rule rather than directly resolving a valueDefinitionAnalyseralready handles attribute resolution during autowiring (lines 222-239 ofDefinitionAnalyser.php), so compilation support is achievableArgumentReflectorTrait::resolveArgumentFromAttribute()method would need to handle the new attribute typeTarget
6.1 minor release