[12.x] Bind abstract from concrete's return type #54628
Merged
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.
Changes
closureReturnTypes
method to the Containerbind
method to allow a Closure in the abstract parameter and process the closure's return types to call bindbind
andsingleton
methods to show they work.Why
I thought this would be a cool thing to use when it comes to the container, I've had it in mind for a while. It follows the same idea as how some test assertion methods use reflection to know what events/jobs etc to expect. Instead this looks at the return type for the concrete Closures for the container.
TDLR; You would be able to provide a type hinted closure and it would use the return type to assign the abstract rather than specifying it with a string.
Example code:
This would allow you to also handle multiple contracts with one Closure:
This could also lead to some future benefits where the container can be more transparent about what abstracts will return without having to call the closure itself.
Notes
Mainly a proof of concept PR, happy to clean up and add additional tests where there might be additional edge cases.
I've added this to Laravel 12. Nothing stopping it going to Laravel 11 but it feels like something to launch with a new version.