Dynamic URLs

Using placeholders to create dynamic routes

Route Placeholders

While adding routes to the Router, we can also use placeholders in the route itself, which get replaced by the actual value used in the requested path.

To add placeholders in a path, use {} and give it a name between the braces.

Router::add_route('GET', '/user/{name}', [HomeController::class, 'show']);

{name} in the above route, will get replaced by the actual value used there at the time of the request. That value can be referenced in the html file that the 'show' method renders by the name $name. Whatever is between the braces, is what the variable name would be that would contain the value used at that place.

In code it would look like

class HomeController {
    public function show($request) {
        VIEW::init('index.html');
}

If we visited /user/shoaib for example, in the index.html file, if we write

<h1> Hello, <?= $name; ?> </h1>

It would output

Hello, shoaib

The rule states that more specific route should be placed first. A route with no placeholders is more specific than the ones with placeholders.

If we have routes that have matching prefixes like:

- /user/admin       # this one is more specific as there are no placeholders.
- /user/{name}      # this one is less specific and should be placed after first one

Adding Multiple Placeholders

We can also add multiple placeholders in a single route, for example

Router::add_route('GET', '/user/{profile}/{name}', [HomeController::class, 'show']);

Now, the $profile and $name can be made available in the index.html file by added them to context as we did above.

The rule of specificity should be followed in here too.

Last updated