[7.x] Add container support for variadic constructor arguments #32454
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.
This PR adds container support for variadic constructor arguments.
See these Twitter discussions for the catalysts for this PR:
The Problem
There is currently no way to support classes that have variadic constructor arguments without breaking out and providing a full factory for a class.
For example:
The only way to do this currently:
It feels heavy handed since we have to manually
make
all four dependencies forFirewall
when all of them should be able to be autowired. Likewise, add another constructor argument, and the container configuration needs to change, even if the new constructor argument could be autowired.The Solution
My ideal situation is to configure classes like this using contextual binding. I only want to specify the dependencies that cannot be autowired.
To me, that looks like this:
Or... better yet...
This PR makes both of these last two configuration styles possible.
Notable Changes
Container::getContextualConcrete
can now return anarray
(only a doc change, but changed expectation)Container::resolveClass
can now return anarray
(docs already have it returningmixed
, but changed expectation)Container::resolveClass
will now return an empty array ([]
) if a value is not defined (better fits with how PHP handles variadic functions when no variadic values are actually passed)ContextualBindingBuilder::give
can now accept an array (only a doc change, but changed expectation)Other Thoughts on Implementation
needs
/give
is best vs addingneedsVariadic
/givesVariadic
or something along those lines. This looks cleanest and probably easiest to adopt, but happy to discuss this.Container::resolveClass
. I started downresolveVariadic
but quickly scaled back as it was duplicating a lot of code and wasn't sure it was worth it.Related to #26950.