Build a feature
This is the "clients" feature from the Booking Tracker example, cut to its essentials: a list of clients and a form to add one. Every feature you build follows the same four files.
| File | Job |
|---|---|
database/migrations/*/app-001-clients.sql | The table |
app/custom.php | Your functions: queries and validation |
public/clients.php | The page: guard, handle the form, render |
app/views/pages/clients.php | The HTML |
Nothing in app/lib/ is touched.
1. The table
database/migrations/sqlite/app-001-clients.sql (see Add a database table for the MySQL version):
CREATE TABLE clients (
id INTEGER PRIMARY KEY AUTOINCREMENT,
user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
name TEXT NOT NULL,
phone TEXT NOT NULL DEFAULT '',
created_at TEXT NOT NULL,
updated_at TEXT NOT NULL
);
CREATE INDEX idx_clients_user ON clients (user_id, name);
With SQLite, that's it: the table is created on the next request that uses the database. With MySQL, run php bin/install.php, or if your host has no command line, see No command line?.
2. The functions
In app/custom.php. Three functions: list, validate, create.
/** Every client of this user, A to Z. */
function client_all(int $userId): array
{
return db_all('SELECT * FROM clients WHERE user_id = ? ORDER BY name', [$userId]);
}
/** Read and check the form. Returns [$errors, $clean]. */
function client_validate(): array
{
$clean = [
'name' => input('name'),
'phone' => input('phone'),
];
$errors = array_filter([
'name' => validate_name($clean['name']),
'phone' => str_length($clean['phone']) > 30 ? 'Phone number must be 30 characters or fewer.' : null,
]);
return [$errors, $clean];
}
function client_create(int $userId, array $c): void
{
$now = now_utc();
db_run(
'INSERT INTO clients (user_id, name, phone, created_at, updated_at) VALUES (?, ?, ?, ?, ?)',
[$userId, $c['name'], $c['phone'], $now, $now]
);
}
Three things to notice. Every query names user_id. Every value reaches the database through a ?. And array_filter drops the fields that passed, leaving only the ones with an error message.
3. The page
public/clients.php, complete:
<?php
declare(strict_types=1);
require __DIR__ . '/../app/bootstrap.php';
allow_methods('GET', 'POST');
$user = require_auth();
$userId = (int) $user['id'];
$errors = [];
$old = [];
$status = 200;
if (is_post()) {
csrf_verify();
[$errors, $clean] = client_validate();
if (!$errors) {
client_create($userId, $clean);
flash('success', "{$clean['name']} added.");
redirect('clients.php');
}
$old = $clean;
$status = 422;
}
view('pages/clients', [
'title' => 'Clients',
'active' => 'clients',
'clients' => client_all($userId),
'errors' => $errors,
'old' => $old,
], 'app', $status);
On success the page redirects instead of rendering. That's Post/Redirect/Get: if the user presses Refresh, the browser repeats a harmless GET and the client isn't added twice.
On failure it falls through and renders the form again, with what the user typed ($old) and what was wrong ($errors).
4. The template
app/views/pages/clients.php:
<section class="panel">
<header class="panel-header"><h2>Your clients</h2></header>
<?php if (!$clients): ?>
<div class="empty-state">
<p><strong>No clients yet</strong></p>
<p class="muted">Add your first client below.</p>
</div>
<?php else: ?>
<div class="table-wrap">
<table class="table">
<thead><tr><th scope="col">Name</th><th scope="col">Phone</th></tr></thead>
<tbody>
<?php foreach ($clients as $client): ?>
<tr>
<td><?= e($client['name']) ?></td>
<td><?= e($client['phone'] ?: '—') ?></td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
</div>
<?php endif; ?>
</section>
<section class="panel">
<header class="panel-header"><h2>Add a client</h2></header>
<form method="post" action="clients.php" class="form panel-body" data-once>
<?= csrf_field() ?>
<div class="field">
<label for="name">Name</label>
<input id="name" name="name" type="text" required maxlength="100"
value="<?= e($old['name'] ?? '') ?>"<?= field_attrs($errors, 'name') ?>>
<?= field_error($errors, 'name') ?>
</div>
<div class="field">
<label for="phone">Phone</label>
<input id="phone" name="phone" type="tel" maxlength="30"
value="<?= e($old['phone'] ?? '') ?>"<?= field_attrs($errors, 'phone') ?>>
<?= field_error($errors, 'phone') ?>
</div>
<div class="form-actions">
<button type="submit" class="btn btn-primary">Add client</button>
</div>
</form>
</section>
The classes (panel, table, form, field, btn) are Core's. csrf_field() is the form token. field_error() prints the message under a field, and field_attrs() marks the input as invalid for screen readers.
Add the menu link as in Add a page, and the feature is done.
Editing and deleting one row
An edit page takes the row's id from the address (client-edit.php?id=12). Anyone can type a different number there, so look the row up with the user's id and treat a miss as "not found":
function client_find(int $id, int $userId): ?array
{
return db_one('SELECT * FROM clients WHERE id = ? AND user_id = ?', [$id, $userId]);
}
// in public/client-edit.php
$client = client_find($id, $userId) ?? abort(404);
Answer 404, not 403. "Forbidden" confirms that client 12 exists in someone else's account; "not found" says nothing.
The full Booking Tracker, with editing, deleting, appointments and a dashboard, is written up on the blog.
The tracker is a private diary: its owner types every appointment in. The version a business's customers book themselves into, with a public booking page and reminder emails, is the Bookings blueprint. It's built with the pattern on this page, plus the parts that only matter once strangers can submit the form.