Caching

Keep a page, a fragment or a region of a template on the server. Choose who shares an entry, what splits it and what clears it.

Updated
On this page

Caching is opt-in. Nothing is kept until a view, fragment or region asks for it, and a write to the content it shows clears it. There are three server-side layers, each narrower than the last:

Layer Keeps Asked for with
Page A whole rendered page cache in the view's index.json
Fragment One {block} of a page, fetched at its :blockname URL {fragment} with cache:
Region Part of a template, inside a normal render {cache}

All three store HTML in site/data/cache/pages.db and share the same rules for who sees an entry, what splits it and what clears it. Files and images have their own browser caching, covered at the end.

Cache what you have measured as slow. A cache that is not needed is one more thing to reason about.

Caching a fragment

Give a fragment a cache: in seconds. Its HTML is stored and served without running the controller or the rest of the page:

<ul
    id="latest"
    n:inner-fragment="cache: 300"
>
    {foreach $page->children('sort=-created, limit=5') as $post}
        {include 'blog/card.latte', p: $post}
    {/foreach}
</ul>

n:inner-fragment makes the element's content a block named by its id, so the block is also reachable at {$page->url()}:latest. n:fragment does the same for the whole element. Another page embeds it by fetching that URL, and the content lands in the element whose id matches the name:

<div
    id="latest"
    hx-get="{p('blog')->url()}:latest"
    hx-trigger="load"
    hx-swap="none"
></div>

A fragment that loads itself after the page is n:lazy. On a normal visit the element shows only its {placeholder}, or nothing without one, and asks for its own :name URL on load. The fetched response carries the content without the trigger, so it never asks for itself again. The page, and its full-page cache entry, holds the empty element, and cache: keeps the fetched content on the server (add client: to let the browser keep it too):

<div
    id="latest"
    n:lazy="cache: 300"
>
    {placeholder}
        {ui skeleton /}
    {/placeholder}
    {foreach $page->children('sort=-created, limit=5') as $post}
        {include 'blog/card.latte', p: $post}
    {/foreach}
</div>

Use this for work that is slow to render, such as syntax highlighting: the page answers at once and the slow part is fetched, and kept with cache:, on its own. The request carries the page's query string, so ?tab= and the like reach the fragment, and the cached copy is kept once per full query.

{placeholder} goes directly inside the element and holds what to show until the content arrives, such as a skeleton or a cheap version of the content. The fetched response leaves it out. Without one the element is empty until it loads, which suits a region that is hidden or fixed in height, such as a tab panel. Give the placeholder the content's height so nothing shifts when it swaps in, and make it readable without JavaScript.

Any page can fetch a fragment, not only its own. The response carries its target, the element whose id is the fragment's name, so the fetching element needs that id and hx-swap="none". Use it for a piece many pages share:

<ul
    id="latest"
    n:inner-fragment="cache: 300"
>
    {foreach $page->children('sort=-created, limit=5') as $post}
        {include 'blog/card.latte', p: $post}
    {/foreach}
</ul>

<aside
    id="latest"
    hx-get="{p('blog')->url()}:latest"
    hx-trigger="load"
    hx-swap="none"
></aside>

Only blocks written directly in the target page's own template can be fetched this way, not blocks inside an {include}d file. If the target's view has a router, it needs a get('') route.

Caching a region

{cache} keeps part of a template inside a normal render. The key is the page URL and query:

{cache 'stats', 600}
    {include 'shop/stats.latte', orders: $orders}
{/cache}

key: replaces the address so several pages share one region. A shared region also needs in: (see below), because the page that holds it must be cleared whenever any of them could change:

{cache 'nav', 300, key: $section->uuid, in: '/'}
    {ui menu, items: $section->children() /}
{/cache}

A hit skips the region entirely, so nothing inside it may set a response header or a variable used after it.

Caching a page

Set cache in a view's index.json to a number of seconds and its pages keep their whole render:

{ "cache": 300 }

A kept page is served after the router runs and before the controllers and the template do, so a router can still refuse, redirect or set headers. Only plain GET requests are kept.

By default the home page holds the entry, so any page write clears it. To tie it to its own branch, write the setting as an object. It is then cleared by a write to the page, a page above it or a page below it:

{ "cache": { "ttl": 300, "scope": "page" } }

With scope: page, content from other branches, such as a menu or a list of related pages, belongs in a {fragment} with in: naming a common ancestor.

A response that started a session, set a cookie or set an HX-* header is not kept. The TTL is cut to the shortest {cache} region inside the page. The response carries Cache-Control: no-cache and an ETag, so a browser or proxy checks with the server on every use and gets an empty 304 while the page is unchanged. It can never serve a stale copy. A view can also let a shared cache in front of the site hold it, see Holding a page at the edge.

Saving a page clears its entry, so the next visitor would wait for the render. To spare them, a web save of a public page whose view sets cache also asks for that page as a signed-out visitor once the response has been sent, which keeps the render again. Only the saved page is rebuilt: the pages above and below it, which the save also cleared, are kept on their first visit. Slow work still belongs in a lazy fragment, because the first render after a deploy or an expiry is a visitor's. Nothing is rebuilt from the command line, with "cache": false, or when the site cannot reach its own URL.

Who sees an entry

Every entry is kept for an audience. You do not set it: PhlatPage watches what the render asks about the visitor and shares the entry as widely as the answers allow.

The render asked One entry for
Nothing about the visitor Everyone
What they hold: role(), can(), isLoggedIn() Each role. guest is a role.
Who they are: $app->session->user() Each signed-in user. Signed-out visitors share one.
The session (a flash message, a CSRF token) Nobody: it is not kept

A signed-out visitor counts too. A block that asked isLoggedIn() of a guest is kept for guests, never shown to a member. So the same tags cover all three cases:

{* Asks nothing about the visitor: one copy for everyone *}
{fragment 'prices', cache: 3600}
    {include 'shop/prices.latte'}
{/fragment}

{* Asks can(): one copy per role *}
{fragment 'toolbar', cache: 300}
    {include 'shop/toolbar.latte'}
{/fragment}

{* Asks for the user: one copy per signed-in user *}
{cache 'orders', 120}
    {include 'shop/orders.latte'}
{/cache}

A view's kept page follows the same rule, so its index.json needs only a TTL:

{ "cache": { "ttl": 300 } }

A key: on {cache} replaces only the address. The audience still applies, so a shared key does not share the entry across users.

A signed-in visitor's kept page is sent private, no-cache, so a shared proxy never holds it.

One render can narrow it for all

A block may ask more of some visitors than of others, such as {if can('orders.view')}{$user->name}{/if}. Once any render of it asked who the visitor is, the block is kept per user for everyone until the entry expires or is cleared. Its guests and its other roles still share their own entries. A narrower audience costs misses, never a leak, and Clockwork's Cache panel shows the key with its audience.

To share the expensive part, keep it in a block of its own that asks nothing about the visitor, and leave the personal part outside it:

<p>Hello, {$user->name}.</p>

<div
    id="catalogue"
    n:inner-fragment="cache: 3600"
>
    {foreach find('view=product, limit=24') as $product}
        {include 'shop/card.latte', p: $product}
    {/foreach}
</div>

A form with a CSRF token, or a block that shows a flash message, stays outside the cached region for the same reason.

What splits an entry

An entry is kept once per value of whatever the render read, and nothing else:

  • Query parameters read through $app->request->query('page'). A parameter nothing read, such as ?utm_source=, creates no new entry. queries(), which reads all of them, keys on the full sorted query.
  • Visitor options read through $app->options->get('theme'). Visitors who chose dark share one copy, and an option the page never reads does not split it.
  • htmx. A partial request has an entry apart from a full page.

Read through those methods, never $_GET or $_COOKIE. A template that reads a superglobal directly is invisible to the cache, and its entry is keyed too coarsely.

What clears an entry

Every entry belongs to a page, and the page tree is the dependency model. Writing a page clears its own entries, the entries of every page above it and everything below it. The home page is above everything, so an entry held there clears on every write. There are no keys to manage.

Event Clears
A page is created, saved, moved or deleted That page's entries, those of its ancestors and those of its descendants
A collection item or file is written, or a History restore The page that owns it and the pages above it
A page move or a History sync Every entry
A user is updated or deleted Only the entries kept for that user
Config, templates or code change Nothing. The entry ends when its TTL does

After a deploy that keeps site/data/cache, run phlat cache:clear. The reference deploy.php gives each release an empty cache.

Holding an entry higher with in:

A fragment that lists pages outside its own page's subtree would stay stale until its TTL ran out. in: names the page that holds the entry, as a literal path, so a write anywhere under that page clears it:

<ul
    id="latest"
    n:inner-fragment="cache: 300, in: '/'"
>
    {foreach find('view=article, sort=-created, limit=4') as $article}
        {include 'article/card.latte', p: $article}
    {/foreach}
</ul>

in: '/' is cleared by every page write. A narrower page such as in: '/blog' is cleared only by writes under /blog. A path that names no page holds nothing, so the region renders every time.

Clearing from an event

A user write clears only that user's entries. A page that shows users to others, such as a team page, is not one of them, so clear it from a hook:

$app->on('user.update:after', fn() => $app->page('/team')->cache()->flush());

Any event works the same way. $page->cache()->flush() empties one page's own entries, and $page->cache()->flush('tree=.') empties the entries a save of that page would clear. flush() takes the find() query over path, user and tree, so flush("user={$uuid}") empties one visitor's entries on every page. From the shell, phlat cache:clear --page=blog/my-post does the same, with --tree for the wider clear.

Example: a members area with an API

A members page shows the signed-in user's orders from a billing API. The call is slow, the data is private to the user and a minute of staleness is fine. The block asks for the user, so it is kept per member and only needs a TTL.

The call lives on the view's Page class, so it runs only when the template asks for it:

<?php
// site/views/members/members.php

declare(strict_types=1);

namespace Phlat;

use Phlat\Toolkit\Http;

class MembersPage extends Page
{
    public function orders(): array
    {
        $user = $this->app->session->user();

        return Http::get(
            "https://billing.example.com/orders?customer={$user->uuid}",
            ['Authorization' => 'Bearer ' . $this->app->config->get('billing.token')],
        )->json();
    }
}

The template holds the orders in a lazy fragment. The list renders only on the fragment's own request, so opening the page makes no API call:

<h1>Your orders</h1>

<ul
    id="orders"
    n:lazy="cache: 60"
>
    <li n:foreach="$page->orders() as $order">{$order['number']}: {$order['status']}</li>
</ul>

Each member gets an entry of their own for a minute. A hit is served before the controller or the template run, so the API is called once per member per minute however often the page opens.

When the data changes on the billing side, the member sees it after the TTL. If your site is told about the change, clear the entry from that handler with $page->cache()->flush() and the next request fetches fresh data.

A page both for members and visitors, with a list that is the same for everyone, splits the work: keep the shared list in a block that asks nothing about the visitor and the member's own block in another.

Holding a page at the edge

A kept page is revalidated on every use, so a CDN in front of the site still reaches the origin each time. A view can allow the CDN to hold it instead. Write edge in the view's cache setting:

{ "cache": { "ttl": 86400, "edge": true } }

A signed-out visitor is then sent Cache-Control: public, max-age=0, s-maxage=86400. A browser still revalidates, and the CDN keeps the page for the TTL.

The CDN keys on the URL alone, so only a response that is the same for everyone with that URL is marked public:

The request Sent
Signed out, no option chosen, a full page public, max-age=0, s-maxage=N
Signed out, with an option cookie set no-cache
An htmx request, answered with a partial no-cache
Signed in private, no-cache

The origin cache is not affected. A render that read an option is still kept once per value of it.

Set the edge up to match. Make the site's HTML eligible for cache, respect the origin TTL, and bypass it for a request with an HX-Request: true header, a cookie starting option_ or the session cookie. A CDN ignores Vary, so these cases cannot be left to the response.

Clearing the edge

Whatever clears the page cache must clear the CDN, or a visitor sees an edit only when the TTL runs out. The site/edge addon does this for Cloudflare. It listens for cache.flush:after and purges the zone, once per request, so a page, item or file write, a move and phlat cache:clear all reach it. List it with the zone id and a token allowed to purge it:

"site/edge": { "zone": "…", "token": "…" }

Keep the token in site/data/env.json, not in the repository. Without a zone and token the addon does nothing. For another CDN, listen for the same event.

A deploy starts with a cache of its own and does not empty the CDN's. Run phlat cache:clear after it, which fires the event.

Holding it in the browser

A kept page or fragment is revalidated on every use, so the browser still makes a request each time. Write client to let the browser keep it for some seconds without asking:

{ "cache": { "ttl": 300, "client": 60 } }
{fragment 'popular', cache: 300, client: 60}…{/fragment}

The response is sent Cache-Control: private, max-age=60 with Vary: HX-Request, Cookie. The browser never keeps it longer than what is left of the server entry, so a client longer than the TTL is cut to it.

A save clears the server copy but cannot reach a browser that already holds one, so client is the staleness you accept for a visitor who has it. Use it for content that is the same for many visitors and rarely edited. Do not put it on a block that a save refreshes for the person who saved it.

Signing in or out changes the session cookie, so the browser asks again and never shows one visitor's copy to the next. An editor, and any request while debug is on, is always sent no-cache. client needs cache. With edge, a signed-out visitor is sent public, max-age=60, s-maxage=86400 instead, so the CDN and the browser each keep it for their own time.

Watching and switching it off

Clockwork's Cache panel lists every get, set and flush with its key, and a row saying why a kept page was or was not stored. The same events are available to your own code as cache.get:after, cache.set:after, cache.flush:after, page.cache:hit and page.cache:skip.

"cache": false in config.json or env.json turns every cache off, and cache.pages.enabled turns off this one. Both are useful while developing a template. phlat cache:clear empties site/data/cache, and phlat cache:clear --page=<path> --tree empties what a save of that page would.

Files and images

Image variants are sent public, max-age=31536000, immutable. A file's url() carries a token from its modification time, so replacing the file changes the URL and the browser fetches the new one. Other files use the files.cache setting. These are browser caches and need no markup.