[HttpKernel] Allow injecting query and request parameters in controllers by typing them with #[QueryParameter]
or #[RequestParameter]
attribute
#49134
+461
−0
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.
We increased the PHPStan level from 8 to 9. This lead to some problems when working with query or request parameters.
For example:
Because Symfony types
Request::get()
asmixed
there is no type safety and you have to assert everything manually.We then learned that we shouldn't use
Request::get()
but use the explicit parameter bag like:This
ParameterBag
is used forrequest
andquery
. It contains interesting methods like:This has the benefit that now the returned value is of a correct type.
Why aren't we being explicit by requiring the parameters and their types in the controller action instead?
Luckily Symfony has a concept called ValueResolver.
It allows you to do dynamically alter what is injected into a controller action.
So in this PR, we introduces 2 new attributes:
#[QueryParameter]
and#[RequestParameter]
that can be used in controller arguments.It allows you to define which parameters your controller is using and which type they should be. For example:
When requesting
/?ids[]=1&ids[]=2&firstName=Ruud&required=3&age=123
you'll get:It even supports variadic arguments like this:
When requesting
/?ids[]=111&ids[]=222
the$ids
argument will have an array with values ['111','222'].Unit testing the controller now also becomes a bit easier, as you only have to pass the required parameters instead of constructing the
Request
object.