Skip to content

Route parameters

Andrea Mecchia edited this page Jul 4, 2018 · 5 revisions

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/snoopy

Where 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.

Simple route 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 (username in this case) can only contain alphanumeric characters A-Za-z0-9 plus 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"]}";
});

Complex route parameters

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];
});

Database >

Clone this wiki locally