[12.x] feat: Add Contextual Implementation/Interface Binding via PHP8 Attribute #55904
+87
−1
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Summary
This PR introduces a new
Provide
attribute that enables contextual dependency binding using PHP 8 attributes, offering a more declarative and intuitive alternative to traditional Service Provider registration for dependency injection.Problem
Currently, Laravel developers must register contextual bindings in Service Providers, which can become verbose and disconnected from the actual usage context:
This approach has several limitations:
Solution
The
Provide
attribute allows developers to specify concrete implementations directly at the point of injection:Key Features
Usage Examples
Basic Usage
With Constructor Parameters
Method Injection
Implementation Details
The
Provide
attribute implements Laravel'sContextualAttribute
interface, ensuring seamless integration with the existing container resolution system. The attribute:make()
method to resolve dependencies with proper parameter injectionBenefits
Backward Compatibility
This enhancement is fully backward compatible:
Requirements
Related Issues
This enhancement addresses common developer pain points around:
Note: I vacillated a lot on naming...
Provides
,Autowire
,Autowired
,Inject
,Make
,Resolve
,ResolveTo
,ResolvesTo
,Bind
,Give
,Service
,Implementation
,Concrete
, etc. also would work, of course.