-
Notifications
You must be signed in to change notification settings - Fork 1
Route parameters
Index > HTTP routing > Basic routing
Route parameters allows us to inject parameters inside request URLs.
For example, a request to retrieve user information from a social network API may look like this:
GET https://social.com/v1/user/snoopyWhere snoopy is the name of the user.
This way of addressing resources is compliant with the concept of URI (Uniform Resource Identifier) and it is usually more readable then using query parameters.
Route parameters are defined per-route using a set of curly braces to enclose the URL component(s) we want to qualify as parameter:
$router->get("/user/{username}", function(){});The name of the parameter (
usernamein this case) can only contain alphanumeric charactersA-Za-z0-9plus the underscore character_
A single parameter contributes to route matching as a sequence of at least one character different from / and space characters. In regex notation: [^\s\/]+.
Parameters are passed as second parameter inside the route action, as an associative array:
$router->get("/user/{username}", function(Request $request, array $args){
echo "username: {$args["username"]}";
});Route parameters cannot be fine-tuned with regular expressions (e.g. restricting the parameter to alphaumeric characters, limiting the size, etc.).
However we can be more flexible about the number of components a single parameter should span over using a quantifier.
The notation is very regex-like:
| type | symbol | description | example |
|---|---|---|---|
| number | {n} |
exactly the number of components specified | {name}{2} |
| range | {n-m} |
a number of components in the range specified | {name}{1-2} |
| any | * |
any number of components (zero included) | {file}* |
| at least one | + |
one or more components | {file}+ |
| at most one | ? |
an optional component | {age}? |
Parameters with quantifiers can yield two types of data: an array of strings or a single string, with the latter being the default.
To change the representation, append a set of square brackets after the parameter name:
$router->get("/user/{name[]}{2}", function(Request $request, array $args) {
$firstName = $args["name"][0];
$lastName = $args["name"][1];
});