Lapis Docs

Data and code

Page functions

A page file can handle more than GET. Functions with an attribute in its setup block answer the HTTP methods: they load the template's data, take forms and serve JSON. The variable you assign a function to does not matter, the attribute does.

<?php // pages/contact.php
use Lapis\Routing\{Get, Post, Middleware};
use Lapis\Middleware\RateLimit;
use Tempest\Http\Request;
use Tempest\Http\Responses\Redirect;

$load = #[Get] fn ($cms) => ['prices' => $cms->data('products')->get()];    // the template's data

$send = #[Post, Middleware(new RateLimit(5, 600))] function (Request $request) {
    if (empty($request->body['email'])) {
        return ['error' => 'Enter your e-mail address.'];   // the page renders again with this
    }

    return new Redirect('/contact?sent=1');
};
?>
<x-layout> … <form method="post"> … </form> … </x-layout>

Methods

The attributes are #[Get], #[Post], #[Put], #[Patch], #[Delete] and #[Query]. For several methods at once, use #[Method('GET', 'POST')]. A request with a method that has no function gets a 405, with an Allow header.

#[Query] is the HTTP QUERY method: a read-only request with a body, such as a search sent as JSON. Send it with a Content-Type, because without one the answer is a 400. PHP only parses form bodies for POST, so send JSON. Like GET, a QUERY request is not checked for cross-site requests, and it never goes into the page cache.

What a function returns

What a function returns decides the answer:

  • A Response goes out unchanged, such as a redirect, a file or a Json.
  • An array becomes template variables, and the page renders again. The #[Get] loader runs too, so the page has its data.
  • In a route file, an array becomes JSON, a string becomes HTML, and nothing becomes a 204.

Answering htmx with a part

A form or a search sent by htmx often needs only one part of the page back. Mark that part with data-lapis-fragment and an id, and point htmx at it: the page renders with the function's result (errors included), and only the marked element is the answer.

<?php
use Lapis\Forms\Fields\Text;
use Lapis\Routing\Post;
use Tempest\Http\Request;

use function Lapis\validate;

$find = #[Post] function (Request $request) {
    $values = validate($request, ['term' => new Text('Term', required: true)]);

    return ['found' => search($values['term'])];
};
?>
<form method="post" hx-post hx-target="#results" hx-swap="outerHTML">
    <input name="term">
</form>
<ul id="results" data-lapis-fragment>
    <li :if="isset($errors['term'])">{{ $errors['term'] }}</li>
    <li :foreach="$found ?? [] as $item">{{ $item }}</li>
</ul>

Without JavaScript the same form posts the page and gets the whole page back. A boosted link, or a target that is not marked, gets the whole page too.

Invalid input answers 422 with the part. htmx 2 swaps no 4xx answer by default, so let it swap a 422, once in your JavaScript:

htmx.config.responseHandling = [
    { code: '204', swap: false },
    { code: '[23]..', swap: true },
    { code: '422', swap: true },
    { code: '[45]..', swap: false, error: true },
];

Parameters

A function asks for what it needs, by name or by type. It may take the route parameters (string $slug), $page, $cms, $site, $request, and any service of the container by its class, such as Db $db or your own classes.

The folder's _middleware.php runs first, then the function's own #[Middleware(…)] attributes, which may be repeated. See Middleware.

Loaders and data-driven pages

A #[Get] function is the template's loader: what it returns becomes the template's variables. When it returns title and description, those go to the browser tab and to search engines.

A [slug].php template with a loader needs no page record. The loader decides whether the page exists, and null answers with a 404. For the sitemap, #[Paths] lists the parameters of every page:

<?php // pages/products/[slug].php
use Lapis\Routing\{Get, Paths};

$load = #[Get] function ($cms, string $slug) {
    $product = $cms->data('products')->findBy('slug', $slug);

    return $product === null ? null : ['product' => $product, 'title' => $product['name']];
};

$paths = #[Paths] fn ($cms) => array_map(fn ($p) => ['slug' => $p['slug']], $cms->data('products')->get());
?>

Caching a loader

A slow loader can keep its result, keyed by the route parameters and the query string. #[Get, Cached(ttl: 600)] keeps it for ten minutes, and #[Get, Cached(tables: ['products'])] keeps it until a record of those tables changes. CACHE_LAPIS_LOADERS_ENABLED=false in .env switches the loader cache off.

Validation

validate() checks the request against a list of fields and returns the cleaned values:

use Lapis\Forms\Fields\{Email, Text};

$values = validate($request, [
    'name' => new Text('Name', required: true),
    'email' => new Email('E-mail'),
]);

It takes the form fields of Lapis\Forms\Fields, with the same types and messages as forms. Data table columns (Lapis\Data\Columns) work too, for example right before writing a record, and the two may be mixed.

Invalid input answers with a 422:

  • For a template, the page renders again with $errors (per field), $old (the sent values) and $error (a summary), and the #[Get] loader runs.
  • For a route file, or a request with Accept: application/json, the answer is JSON: {"ok": false, "error": "…", "errors": {"name": "Required field."}}, the same as the editor API.

When a data table's create() or update() fails, the errors show the same way.

Route files

A page file without a template returns its function instead. Use one for a feed, an API or a webhook:

<?php // pages/webhook/[source].php
return #[Post, CrossSite] function (string $source, Request $request): array {
    return ['ok' => true];      // array → JSON; string → HTML; nothing → 204
};

A route file needs no page record, and it stays out of the page cache and the sitemap. ./lapis routes marks it. For several methods, return a list of functions, or an array such as ['POST' => fn …].

Security

Page functions are protected by default:

  • POST, PUT, PATCH and DELETE are only taken from this site, which the browser's Sec-Fetch-Site header proves. GET, HEAD, QUERY and OPTIONS are safe methods, so they are not checked.
  • #[CrossSite] lets other servers in, for webhooks. Then check the caller yourself, for example with a signed webhook: Webhook::verify($request, env('SHOP_WEBHOOK_SECRET'), header: 'X-Signature'). It also accepts algorithm: (default 'sha256'), prefix: (such as 'sha256=' for GitHub) and base64: true.
  • To let the browsers of other sites call a page with fetch(), list those sites in a Cors middleware.

API keys

For programs that call the site, protect a function with a key: #[Post, ApiKey('SHOP_API_KEY')] (without an argument, it reads LAPIS_API_KEY). The caller sends Authorization: Bearer <key> or an X-Api-Key header. The keys come from .env, at least 16 characters each, and several may be given separated by commas, so that they can be rotated.

Every caller needs a valid key by default. Pass browser: true to let same-site browser requests skip the key (useful for public pages calling an endpoint from JavaScript, though Sec-Fetch-Site is browser CSRF protection rather than client authentication). A request without a valid key gets a 401, and an answer to a keyed request never goes into the page cache.