Routing

Router files map URL sub-paths to closures. A page's view picks the router.

Updated
On this page

How routing works

On each request, PhlatPage walks the URL from the deepest segment upward until it finds a page. It loads that page's view router and matches the remaining sub-path against its routes.

A page at /shop/ with view shop is handled by site/views/shop/router.php. The sub-path is relative to the page URL, so the same router works wherever the page sits in the tree.

If the view has no router, the page renders on GET. If it has one and no route matches, the request 404s.

Router files

A router file returns a callable that registers routes on $page->router:

<?php

use Phlat\App;
use Phlat\Page;

return function (App $app, Page $page): void {
    $page->router->get('',        fn() => $page);
    $page->router->get('archive', fn() => ...);
    $page->router->post('contact', fn() => ...);
};

get, post, put, patch and delete register a route for that verb; any matches every verb.

A handler returns $page to render the current page, or a different Page to render that one. Res::redirect() and the Hx:: exit helpers exit internally and return nothing.

Dispatch order

Before matching, PhlatPage loads other router files for their hooks only, discarding the routes they register:

  1. The global router, views/router.php of the view's owner: your site's for a site view, the addon's or the core's for an @alias view
  2. Each ancestor page's view router, root first
  3. The current page's view router, whose routes are kept

There is no per-page router override. Resolution is by view.

Route parameters

Token Matches
{any} one path segment, including empty
{all} everything after this point, across slashes, including empty
{alpha} one non-empty segment, letters only
{alphanum} one non-empty segment, letters and digits
{num} one non-empty segment, digits only
{slug} one non-empty segment, lowercase a-z and 0-9 with single hyphens between

Use the narrower tokens for identifiers, so a malformed or empty value 404s in the router instead of reaching the handler. Captures are passed to the handler as positional arguments:

$page->router->get('post/{slug}',          fn($slug) => ...);
$page->router->patch('pages/{all}',        fn($path) => ...);
$page->router->get('archive/{num}/{slug}', fn($year, $slug) => ...);

A {all} directly after a literal / also matches the bare segment: 'new/{all}' matches new as well as new/anything/nested.

before() and after() hooks

Register hooks on $page->router from any router file. before runs once, right before route matching, after every router in the dispatch chain has loaded. after runs once a handler has resolved a result page, right before it is returned.

A hook that wants to stop the request redirects or throws. There is no return value to block with.

// Runs for every page under this section
$page->router->before(function ($app, $page) {
    $app->session->requireLogin();
});

Fragment URLs

A :blockname suffix renders only that {block} of the page's template, so HTMX can fetch a region without a dedicated route. It works for GET automatically, and is parsed into $app->request->block.

In a template, isFragmentRequest() is true for such a request.

<a href="{$page->url()}" hx-get="{$page->url()}:results">Results</a>

{partial '#target-id'} lets a block say where it lands, in place of an hx-target on the link. The argument is an hx-target selector, used as written, so 'closest .header' works too. On an HTMX fragment request it wraps its content in <template hx type="partial" hx-target="#target-id" hx-swap="innerHTML">, which HTMX 4 places by itself. On a full page it adds nothing. swap: changes the strategy: {partial '#target-id', swap: 'outerHTML'}.

Caching

A page, a {fragment} or a {cache} region can be kept on the server for a number of seconds. See Caching.

Visitor options

$app->options stores choices the server renders, such as a theme or a dismissed banner, in a cookie. Declare each one in config as a slug key and a list of allowed values. The first value is the default, and a cookie can only ever hold a declared value.

"options": {
    "theme": ["default", "dark"]
}

$app->options->get('theme') returns the visitor's value or the default, and set('theme', 'dark') changes it. Setting an option back to its default removes the cookie. A cached page or fragment is kept once per value of each option its render read through get() (see Caching). The core options view takes the change: a page with that view accepts a POST of value to {page url}/{key}, then redirects back to the referring path on your own site. An htmx request gets an empty 204 instead, for a page that applies the change in place.

Example

Use the Toolkit in handlers (Res, San, $app->session), never raw headers, superglobals or echo.

<?php

use Phlat\App;
use Phlat\Page;
use Phlat\Toolkit\Res;
use Phlat\Toolkit\San;

return function (App $app, Page $page): void {
    $page->router->before(function ($app, $page) {
        $app->session->requireLogin();
    });

    $page->router->get('', fn() => $page);

    $page->router->post('', function () use ($app, $page) {
        $name = San::text($app->request->post('name') ?? '');
        $page->session()->flash('flash', "Hello, {$name}.");
        Res::redirect($page->url());
    });
};