--- url: https://docs.tinytank.dev/1.x.md --- # What is TinyTank? ::: warning Status: beta (0.x) TinyTank runs real sites, but it's young: few sites run on it so far, and its API may still change between minor versions (each release's notes in the [changelog](https://github.com/tinytankphp/framework/blob/main/CHANGELOG.md) say what to update, see [Updating TinyTank](./extending/updating)). Review it as you would any dependency before relying on it, and keep it updated: security fixes go into the latest release only ([reporting a vulnerability](./security#reporting-a-vulnerability)). Provided as is, without warranty, under the MIT license. ::: TinyTank is a small PHP framework for sites that are **mostly static but need a little server-side life**: a marketing site with a blog, a documentation hub, a tool with a single interactive page. It gives you routing, Twig templates, reactive UI through [Datastar](https://data-star.dev), a Markdown blog, translations and SEO, without a database or an admin panel. TinyTank is freely inspired by [Craft CMS](https://craftcms.com), for its Twig-first templates, content that templates query rather than receive, and image transforms, and by [Datastar](https://data-star.dev), for its hypermedia approach: the server renders HTML, and the browser stays light. Everything a request needs (compiled routes, Twig templates, parsed blog posts, translations, the Vite manifest) is built ahead of time into plain PHP files in `var/cache`. Opcache keeps those in shared memory, so a production request does no parsing, no database queries and no file scanning. ```twig {# A live search box: Datastar calls the server, which renders a Twig partial back. #} ``` ## What you get | Area | What TinyTank provides | |---|---| | **Routing** | Symfony Routing, compiled to a PHP array; controllers or closures; named routes | | **Templates** | Twig, compiled to PHP classes; `path()`, `t()`, `vite()`, `seo_tags()` and more | | **Reactivity** | Datastar over server-sent events, with a Craft-style Twig API and signed template URLs | | **Content** | A Markdown blog: one folder per post with its images, drafts, tags, search, pagination | | **Languages** | `/it/…`-style URLs, `\|t` translations with plurals, a language switcher, translated posts | | **SEO** | Titles, canonical URLs, Open Graph, Twitter cards, JSON-LD, hreflang, sitemap, Atom feeds | | **Frontend** | Vite + Tailwind CSS with hot reload, inside DDEV | | **Security** | Stateless CSRF protection, escaped Markdown, secrets only in the environment | | **Deployment** | One command that compiles everything and refreshes the web server's Opcache | | **Extending** | Services, Twig extensions, console commands and deploy steps, without editing the framework | ## Who it's for TinyTank suits developers who know PHP and Twig and want a site that is fast, cheap to host and easy to reason about, without a CMS. It is deliberately small: the framework itself is a few thousand lines that you can read in an afternoon. It is **not** a fit when you need user accounts, a database-backed admin, or editors who can't work with Markdown files and git. Reach for a full framework or a CMS in those cases. ## How a site is built on it A new site starts from the **TinyTank skeleton** ([tinytankphp/tinytank](https://github.com/tinytankphp/tinytank)), which installs the framework, the [`tinytank/framework`](https://github.com/tinytankphp/framework) package, with Composer. The site adds its own routes, controllers, templates and content, and updates the framework with `composer update`. [Install TinyTank →](./getting-started/installation) --- --- url: https://docs.tinytank.dev/1.x/philosophy.md --- # Philosophy A few principles explain most of TinyTank's design decisions. Knowing them makes the rest of the documentation predictable. ## Compile ahead of time Most of a website changes only when you deploy. TinyTank moves the work there: `bin/console deploy` compiles routes, templates, blog posts, translations and the asset manifest into PHP files, and the web server's Opcache keeps them in memory. At request time, PHP mostly looks things up. In development (`APP_DEBUG=1`) nothing is cached, so every change shows up immediately. ## No database Content is Markdown in `content/`, configuration is PHP in `config/` plus environment variables, and anything per-visitor lives in the browser. No database means nothing to migrate, back up or secure, and a deploy is a file copy. ## Proven libraries, little glue TinyTank doesn't reinvent infrastructure. Requests and responses come from `symfony/http-foundation`, routing from `symfony/routing`, CSRF protection from `symfony/security-csrf`, Markdown from `league/commonmark`, structured data from `spatie/schema-org`, translations from `symfony/translation`, and assets from Vite. TinyTank's own code is the layer that ties them together: the kernel, the Datastar Twig extension, the blog compiler, the Vite helper. ## Every page is the same for everyone There are no sessions. CSRF protection checks the browser's origin headers instead of a token, so pages carry no per-visitor data and can be cached publicly (every page gets an ETag, and a browser that already has the page gets a `304` instead of it again). Absolute URLs come from configuration, never from the request's `Host` header, so a forged header can't poison a cached page. ## Fail loudly A misplaced post, a broken image link, a date that doesn't match its folder, a translation for a language that isn't configured: TinyTank stops with a message naming the file, in the browser during development and in `deploy`. Silent failures are the ones that reach production. ## The framework is a dependency A site starts from the skeleton and installs the framework (`tinytank/framework`) with Composer. It extends TinyTank from the outside, through `config/bootstrap.php`, `src/`, `templates/` and `content/`, and never edits `vendor/`. Framework improvements reach every site with `composer update tinytank/framework`. See [Building a site on TinyTank](./extending/). ## Content is asked for, not handed out Templates get context automatically (`site`, `seo`, `datastar`), but never content: they query what they need, like Craft CMS's element queries (`posts().tag('php').limit(3).all()`). A template then shows at a glance which content it depends on. See [Querying content](./basics/querying). ## Where TinyTank stops TinyTank is for sites whose content is files, edited by people comfortable with Markdown and git. Its content types stay few and concrete: the **blog** for dated articles, **data collections** for repeating structured data (like Craft's channels), and **content pages** for one-offs (like Craft's singles, nested like a structure). There are no configurable "section types". If a site needs an admin UI for editors, a database, user accounts or permissions, relations between entries, revisions, or field layouts per entry type, use a CMS such as Craft instead. Rebuilding those here would only produce a worse CMS. --- --- url: https://docs.tinytank.dev/1.x/getting-started/installation.md --- # Installation ## Requirements * **PHP 8.4** with the `intl`, `mbstring`, `xmlwriter` and `opcache` extensions (Composer checks all but `opcache`), and **GD or Imagick** with WebP support for responsive images * **Composer 2** * **Node.js 22+** and npm, for the asset build * For local development: **[DDEV](https://ddev.com)** (recommended), which provides all of the above in Docker ## Create a site A TinyTank site starts from the **skeleton**, [tinytankphp/tinytank](https://github.com/tinytankphp/tinytank). With Composer: ```sh composer create-project tinytank/tinytank my-site cd my-site && git init ``` Composer copies the skeleton, installs the framework (the `tinytank/framework` package, from [Packagist](https://packagist.org/packages/tinytank/framework)), then **prepares the site** for you: * names it after its folder: `composer.json`, `package.json`, the DDEV project (`my-site.ddev.site`); * creates `.env` with a fresh `APP_SECRET`, the local address and debug mode on; * lets git track `composer.lock`, so every server installs exactly what you tested; * points CI at that lock file, and removes the files about developing TinyTank itself (`ROADMAP.md`, `CONTRIBUTING.md`, TinyTank's `LICENSE` and `SECURITY.md`); * asks whether to keep **the examples** (Datastar demos, an FAQ, sample posts, an Italian translation): keep them to learn from, and remove them later with `php bin/console site:clean` ([Starting a site](./checklist#_3-the-starter-content)). Without a terminal (`--no-interaction`) it keeps them. Run by hand, `php bin/create-site.php --remove-examples` (or `--keep-examples`) decides up front. ::: details With GitHub's "Use this template" button On [tinytankphp/tinytank](https://github.com/tinytankphp/tinytank), click **Use this template** to create your site's repository, clone it, then run the preparation yourself, once: ```sh git clone git@github.com:you/my-site.git && cd my-site php bin/create-site.php ``` ::: ## Configure `.env` holds the settings that differ per machine; the preparation step filled in the essentials: ```ini APP_SECRET=… # signs Datastar requests; generated for you APP_URL=https://my-site.ddev.site # your site's public URL, no trailing slash APP_DEBUG=1 # development mode ``` `APP_URL` is used for every absolute URL (canonical links, Open Graph, sitemap, feeds). Both `APP_SECRET` and `APP_URL` are required: the app refuses to boot without them. A new secret: `openssl rand -hex 32`. See [Configuration](../basics/configuration) for everything else. ## Run it with DDEV ```sh ddev start ddev composer install # after the template button: ddev composer update ddev npm install ddev npm run dev # Vite + Tailwind with hot reload ``` Open `https://my-site.ddev.site`. Editing a template, a post or a translation reloads the page; CSS changes apply without a reload. ::: warning Assets first Pages need either the Vite dev server (`npm run dev`) or a build (`npm run build`): without one, every page is an error saying "Vite manifest not found". (The tests are the exception: they render pages without asset tags until there's a build.) ::: ::: details Without DDEV Any PHP 8.4 setup works. Point the web server's document root at `public/` and send every request that isn't a file to `public/index.php`. For a quick look: ```sh composer install && npm install && npm run build php -S localhost:8000 -t public public/index.php ``` `public/index.php` lets PHP's built-in server deliver the files in `public/` (built CSS and JS, images) itself. The Vite dev server is configured for DDEV; outside it, run `npm run build` after asset changes, or adjust `server.origin` in `vite.config.js`. ::: ## Check that everything works ```sh ddev composer test # your site's tests (PHPUnit) ddev composer analyse # PHPStan ``` ## Next steps * [Starting a site](./checklist): the checklist for your first hours with a new site * [Project structure](./structure): where everything lives * [Your first page](./first-page): a content page, a page with a controller, a little interactivity ::: tip Working with an AI coding agent The skeleton's `AGENTS.md` tells coding agents (Claude Code, Codex, Cursor…) how a TinyTank site works and which habits from other frameworks don't apply. For the full docs in one request, point them at [`llms-full.txt`](https://docs.tinytank.dev/llms-full.txt) (index: [`llms.txt`](https://docs.tinytank.dev/llms.txt)); every page also exists as Markdown, with `.md` added to its URL. ::: --- --- url: https://docs.tinytank.dev/1.x/getting-started/checklist.md --- # Starting a site `composer create-project` (or `php bin/create-site.php` after GitHub's template button) has already named the site, created `.env` and prepared git and CI: see [Installation](./installation#create-a-site). This checklist is what's left: the decisions only you can make. Tick them off in your first hours with a new site. ## 1. Run it ```sh ddev start ddev npm install && ddev npm run dev ``` Pages need the dev server running (or a `npm run build`); without one they're an error saying "Vite manifest not found". Open `https://my-site.ddev.site`, and keep the [style guide](#the-style-guide) at `/style-guide` open in another tab while you work on the design. ## 2. Your site's identity * \[ ] **Name, description, author and share image**: `site` in `config/app.php`. Each can be one value or one per language ([Languages](../features/languages#the-site-s-name-description-and-share-image)). * \[ ] **Languages**: `language` and `languages` in `config/app.php`, and a `translations/.php` for each ([below](#languages)). * \[ ] **Logo and favicon**: the skeleton's placeholders are `resources/icons/tinytank.svg` (shown in the header as `icon-[app--tinytank]`) and `public/favicon.svg`. Replace them with your own; renaming the icon file changes its class name, so update `templates/_layout.twig` too. * \[ ] **Colours and fonts**: the `@theme` block in `resources/css/app.css`, where each colour is a light and dark pair, and the font import above it ([Fonts & icons](../features/fonts-icons), [Dark & light theme](../features/theme)). * \[ ] **Check the colours** in both themes once they're yours: `npm run build && npm run test:a11y` ([Checking](../accessibility/checking)). A new palette often fails contrast in one theme; see [Colour and contrast](../accessibility/contrast). Optionally, check before every push: `git config core.hooksPath .githooks`. ## 3. The starter content The skeleton comes with **examples**, so you can see how things fit together: Datastar demos on the home page (a live search, a like button, a sound you can play, a server clock), an FAQ as a data collection, two blog posts and a draft, and an Italian translation of everything. `create-project` asks whether to keep them; when you're done learning from them, one command removes them all, with their tests: ```sh php bin/console site:clean # lists what goes, then asks php bin/console site:clean --dry-run # only lists ``` It deletes the files listed in `.examples` and the blocks marked `example:start` … `example:end` in the site's config, templates and tests, then `.examples` itself. What's left is a working site whose tests pass: an English home page with your site's name and latest posts, the blog, About, Contact, Privacy and the style guide. Until you run it, the home page says how, and `deploy` reminds you. * \[ ] **Remove the examples** (`site:clean`), or keep the ones you want: delete the marked block around something to keep it, then clean. The pages that stay are starting points to adapt: | What | Where | Tests that check it | |---|---|---| | The home page | `templates/index.twig`, `src/Controller/HomeController.php` | `tests/PagesTest.php` | | Pages: About (with a child page), Contact (with its form) and Privacy | `content/pages/`; Contact and Privacy are worth adapting rather than deleting | `tests/PagesTest.php`, `tests/ContactTest.php`, `tests/CdnTest.php`, `tests/e2e/contact.spec.js` | | The style guide (below) | `content/pages/style-guide/` | `tests/PagesTest.php`, `tests/e2e/style-guide.spec.js`, and the browser tests that use its image and video (`accessibility`, `images`, `no-javascript`, `video`) | When you change or delete one, update the tests listed next to it, then run `ddev composer test` and the [browser tests](../testing#browser-tests). ### Languages `site:clean` leaves an English-only site; the language switcher disappears by itself with one language. For another language, or several: list them in `languages` in `config/app.php` (and set `language` to the main one), add `translations/.php`, and give pages and posts their `index..md` versions ([Languages](../features/languages)). An Italian-only site: change `language` and `languages` to `it`, and copy `translations/it.php` from the skeleton. ### The style guide `/style-guide` shows every element a post or page can contain (text, headings, lists, quotes, code in several languages, tables, images, video) in your site's design, in light and dark mode. It's an [unlisted](../content/pages#unlisted-pages) page: reachable by its address, but not in search engines, the sitemap or the menus. * \[ ] While designing: keep it, and give the address to your designer. * \[ ] Before going live: keep it (it's harmless) or delete `content/pages/style-guide/` and the test that checks it (`testTheStyleGuideShowsEveryElementButStaysUnlisted` in `tests/PagesTest.php`, `tests/e2e/style-guide.spec.js`); the image and video browser tests open it too, point them at a page of yours. ## 4. Contact and privacy * \[ ] **Where the contact form goes**: `CONTACT_TO` and the mailer (`MAILER_DSN`, `MAILER_FROM`) in `.env` ([Forms](../features/forms)). In DDEV, Mailpit catches every message. * \[ ] **The privacy page** (`content/pages/privacy/`) describes the skeleton's defaults. Make it describe your site: what the contact form does with messages, the log ([Logging](../features/logging)), and anything you add, such as videos, a CDN or analytics. ## 5. Licenses * \[ ] **Changed a font, the icons or added a script?** Update `public/third-party-licenses.txt` and the `/*! … */` notices ([Fonts & icons](../features/fonts-icons#licenses)); `tests/LicensesTest.php` checks them. * \[ ] **Your site's own license**: `composer.json` says `proprietary`. Change it if your site's code is open source, and add a `LICENSE` file. ## 6. Commit * \[ ] The first commit, with `composer.lock`, then push to your site's repository. ## Before going live The [production checklist](../deployment/#production-checklist): `.env` on the server, `APP_DEBUG` off, the web server, Opcache, HTTPS, email, logs and, if you use one, the CDN. --- --- url: https://docs.tinytank.dev/1.x/getting-started/structure.md --- # Project structure ``` my-site/ ├── bin/console Console entry point: deploy, cache:clear, your commands ├── config/ │ ├── app.php Settings: secret, URL, languages, blog, site defaults │ ├── bootstrap.php The app's extension point: services, Twig additions, deploy steps │ ├── collections.php Data collections and their fields │ ├── forms.php Forms: fields, recipients, spam checks │ ├── globals.php Values every template can read (social links, contacts) │ ├── redirects.php Pages that moved: old path → new path │ └── routes.php Routes → controllers ├── content/blog/ Blog posts, one folder each (see "The blog") ├── content/pages/ Content pages: About, Privacy… one folder each (see "Content pages") ├── content// Data collection items, e.g. content/faq/ (see "Data collections") ├── packages/ Empty (.gitkeep); used by TinyTank maintainers, see Contributing ├── public/ Web root: index.php, build/ (Vite), media/ (published post files) ├── resources/ Frontend sources: js/app.js, js/pages/*.js, css/app.css, icons/*.svg ├── src/ Your PHP code (namespace App\): Controller/, Command/, … ├── templates/ Twig templates; _partials/ are rendered by Datastar requests ├── tests/ Your app's tests ├── translations/ UI texts per language: en.php, it.php, … ├── var/cache/ Compiled caches (safe to delete) ├── var/deploy/ deploy's next build, and the previous one (for deploy --rollback) ├── var/log/ The log, one file per day (see Logging) ├── var/state/ Kept across deploys: the forms' rate limits ├── vendor/tinytank/framework/ ★ The framework, installed by Composer: never edit it ├── .env Local environment (never committed) ├── AGENTS.md Instructions for AI coding agents (CLAUDE.md points to it) ├── composer.json Your app's dependencies; requires tinytank/framework └── vite.config.js Your entry points and Vite plugins ``` ## The framework is a package The framework is the `tinytank/framework` package from [tinytankphp/framework](https://github.com/tinytankphp/framework). Composer installs it into `vendor/tinytank/framework`, together with its own dependencies (Symfony components, Twig, CommonMark…); your `composer.json` only requires `tinytank/framework`. Framework code never depends on `App\` classes. ::: warning Never edit vendor/ Everything a site needs to change has an extension point in your own files. Framework updates arrive with `composer update tinytank/framework` (see [Updating TinyTank](../extending/updating)), which would overwrite any edit in `vendor/`. ::: ## What's yours, what's TinyTank's | Yours (edit freely) | TinyTank's (don't edit in a site) | |---|---| | `config/`, `src/`, `templates/`, `content/`, `translations/`, `resources/`, `tests/` | `vendor/tinytank/framework/` | | `public/index.php`, `bin/console` (three-line entry points) | its Vite plugin, `resources/vite/tinytank.js` | | `vite.config.js` (entry points, extra plugins) | its test base class, `TinyTank\Testing\KernelTestCase` | ## Namespaces | Namespace | Directory | |---|---| | `TinyTank\` | `vendor/tinytank/framework/src/` | | `App\` | `src/` | | `App\Tests\` | `tests/` | --- --- url: https://docs.tinytank.dev/1.x/getting-started/first-page.md --- # Your first page TinyTank has two kinds of pages, and most sites need far more of the first: * **A content page**: a Markdown file in `content/pages/`. Its folder is its URL. No route, no controller. Use it for anything that is text and images: About, Team, Services, Privacy. * **A page with a controller**: a route, a PHP class and a Twig template, for pages that compute something on each request. This guide makes one of each, then adds a little interactivity. ## 1. A content page Create `content/pages/team/index.md`: ```md --- title: Our team summary: The people behind the studio. --- We are three designers and a developer, working from a small studio by the sea. ## What we do Brand identities, websites and the occasional illustration. ``` Open `/team`. That's all: the page has its title, meta description and canonical URL, it's in the sitemap, and the skeleton's menu lists it (menus are [queries](../basics/querying) over pages). An Italian version is `index.it.md` in the same folder. Images go in the folder next to `index.md`. The skeleton already has About, Contact and Privacy built this way. See [Content pages](../content/pages) for templates per page, child pages, translated URLs and [unlisted pages](../content/pages#unlisted-pages); repeating items with the same fields (services, team members, products) are a [data collection](../content/collections). ::: warning One URL, one owner A route and a content page can't share a URL: `deploy` stops when a route hides a page. Don't create an `/about` route while `content/pages/about/` exists. ::: ## 2. A page with a controller A page that changes on every request, say a studio's opening hours with "open now" or "closed now", needs a controller. Add a route to `config/routes.php`: ```php use App\Controller\HoursController; return static function (Kernel $app): void { // …existing routes $app->get('/hours', HoursController::class, 'hours'); }; ``` The third argument is the route's **name**: templates link to it with `path('hours')`, and TinyTank adds the language prefix (`/it/hours`) on Italian pages. Create `src/Controller/HoursController.php`: ```php format('G'); $this->app->seo ->title($this->t('Opening hours')) ->description($this->t('When you can visit the studio.')); return $this->render('hours.twig', ['open' => $hour >= 9 && $hour < 18]); } } ``` And `templates/hours.twig`: ```twig {% extends '_layout.twig' %} {% block content %}

{{ 'Opening hours'|t }}

{{ 'Monday to Friday, 9:00 to 18:00.'|t }}

{{ open ? 'Open now'|t : 'Closed now'|t }}

{% endblock %} ``` The layout prints the ``, meta description, canonical URL, Open Graph tags and the language switcher from what the controller set on `seo`. Italian texts go in `translations/it.php`, keyed by the English text: ```php 'Opening hours' => 'Orari di apertura', 'Open now' => 'Aperto ora', ``` ::: tip Pages are cached by browsers and CDNs TinyTank pages are public and revalidated with an ETag: a page whose content depends on the time is fine (the ETag changes with it), but anything personal to a visitor isn't: call `$this->app->noStore()` for such a response (see [CDN caching](../deployment/cdn#not-at-the-cdn-or-nowhere)). ::: ## 3. A little interactivity Interactivity uses [Datastar](../basics/datastar): HTML attributes, no JavaScript to write, and no inline `<script>` (the Content Security Policy blocks it). There are two kinds of state. **State that stays in the browser**, for things the server doesn't need to know: a counter, an open menu, a selected tab. A **signal** and an expression: ```twig <div data-signals="{count: 0}"> <button data-on:click="$count++">{{ 'Add one'|t }}</button> <span data-text="$count"></span> </div> ``` **The server's answer**, when the server must check, compute or look something up: search, a form, "is this slot free?". A **template action** renders a Twig partial on the server with the browser's signals as `signals`, and patches the result into the page: ```twig {# in the page #} <div data-signals="{count: 0}"> <button data-on:click="{{ datastar.post('_partials/count') }}">{{ 'Add one on the server'|t }}</button> <p id="count">0</p> </div> {# templates/_partials/count.twig #} {% set count = (signals.count ?? 0) + 1 %} {% apply patch_elements %}<p id="count">{{ count }}</p>{% endapply %} {% do patch_signals({count: count}) %} ``` `patch_elements` replaces the element with the same `id`, and `patch_signals` updates the signal for the next click. A partial that queues nothing has its whole output patched as elements; as soon as it queues an event (here `patch_signals`), only the queued events are sent, so its HTML needs `{% apply patch_elements %}` too. Prefer browser state when it's enough; reach for the server when it has to decide. More in [Datastar](../basics/datastar) and [JavaScript & Datastar](../features/javascript). ## Next * [Content pages](../content/pages) and [Data collections](../content/collections) * [Routing](../basics/routing): parameters, requirements, methods * [Templates](../basics/templates): every Twig function TinyTank adds * [Testing](../testing): checking pages and actions with PHPUnit --- --- url: https://docs.tinytank.dev/1.x/basics/configuration.md --- # Configuration TinyTank has two places for settings: * **`config/app.php`**: the site's settings, committed to the repository. * **Environment variables**: per-server values and secrets, never committed. In development they come from `.env`. ## Environment variables and `.env` `config/app.php` reads secrets and per-server values with `getenv()`. Locally, they come from a `.env` file in the project root (loaded by `symfony/dotenv`). On a server, set them as real environment variables, or in that server's own `.env`. **Real environment variables always win** over `.env`: anything the server already sets (DDEV's `web_environment`, PHP-FPM's `env[...]`, nginx's `fastcgi_param`, Apache's `SetEnv`) is never overridden by the file. `.env.example` lists every variable and is the only env file that's committed. Copy it to `.env` to start. The full list is in the [environment reference](../reference/environment). ::: warning Secrets stay on the server `APP_SECRET` and anything else sensitive belong in the environment, never in `config/`, templates or JavaScript. Vite only inlines variables prefixed `VITE_PUBLIC_` into the frontend bundle, so server variables can't leak there by accident. ::: ## `config/app.php` ```php return [ 'secret' => getenv('APP_SECRET') ?: throw new RuntimeException('APP_SECRET is not set.'), 'debug' => getenv('APP_DEBUG') === '1', 'url' => $url, // from APP_URL, validated 'trusted_proxies' => [...], // from APP_TRUSTED_PROXIES 'language' => 'en', 'languages' => [ 'en' => ['name' => 'English', 'locale' => 'en_US'], 'it' => ['name' => 'Italiano', 'locale' => 'it_IT'], ], 'blog' => ['per_page' => 20], 'site' => [ 'name' => 'TinyTank', 'description' => 'A database-free PHP micro framework…', 'image' => null, // default share image, e.g. '/images/og-default.png' 'author' => null, // for blog posts and the feed; defaults to the site name ], ]; ``` Every key is described in the [configuration reference](../reference/config). ## Debug mode `APP_DEBUG=1` is development mode: * nothing is cached: routes, templates, posts and translations are rebuilt on every request * blog drafts are visible * errors show Symfony's exception page, and PHP warnings throw * pages load assets from the Vite dev server while `npm run dev` runs * Twig's `strict_variables` is on, so a typo in a variable name is an error Leave it unset (or `0`) in production: errors are logged and visitors get a generic error page. ## Overriding settings in code `Kernel::boot()` accepts overrides that are merged over `config/app.php`. The test suites use this to point the app at fixture content: ```php $app = Kernel::boot($root, debug: false, overrides: [ 'content_dir' => __DIR__ . '/data/content', 'cache_dir' => sys_get_temp_dir() . '/my-cache', 'blog' => ['per_page' => 1], ]); ``` --- --- url: https://docs.tinytank.dev/1.x/basics/routing.md --- # Routing Routes are declared in `config/routes.php`, which returns a function receiving the kernel: ```php use App\Controller\BlogController; use App\Controller\HomeController; use TinyTank\Kernel; return static function (Kernel $app): void { $app->get('/', HomeController::class, 'home'); $app->get('/blog', [BlogController::class, 'index'], 'blog'); $app->get('/blog/{slug}', [BlogController::class, 'show'], 'blog_post', ['slug' => '[a-z0-9-]+']); $app->post('/contact', [ContactController::class, 'send'], 'contact'); }; ``` Under the hood this is the [Symfony Routing](https://symfony.com/doc/current/routing.html) component, so placeholders, requirements and named routes behave as they do in Symfony. ## Defining routes ```php $app->get(string $path, $handler, ?string $name = null, array $requirements = [], int $priority = 0, bool $sitemap = true); $app->post(string $path, $handler, ?string $name = null, array $requirements = []); $app->route(string|array $methods, string $path, $handler, ?string $name = null, array $requirements = [], bool $csrf = true, int $priority = 0, bool $sitemap = true); ``` `route()` takes one or several HTTP methods (`['PUT', 'PATCH']`) and can switch off the [CSRF check](../security#csrf-protection) for a route that must accept requests from other sites, such as a webhook (`csrf: false`). A GET route without placeholders is listed in `/sitemap.xml`; `sitemap: false` keeps out a page that isn't one on its own, such as the list of posts the blog's search loads (`$app->get('/blog/search', …, 'blog_search', sitemap: false)`). Routes are tried in the order they're defined, higher `priority` first. A catch-all such as the [content pages](../content/pages) route (`/{path}`) uses `priority: -1`, so every other route wins, even one added later. ## Handlers A handler is one of: | Handler | Example | |---|---| | A controller method | `[BlogController::class, 'show']` | | An invokable controller | `HomeController::class` (calls `__invoke`) | | A closure | `fn () => $app->render('about.twig')` | Controllers are only created when their route matches. See [Controllers](./controllers). ## Parameters Placeholders in the path arrive as **named arguments**: ```php $app->get('/blog/{slug}', [BlogController::class, 'show'], 'blog_post', ['slug' => '[a-z0-9-]+']); public function show(string $slug): string|Response { … } ``` The fourth argument holds a regular expression per placeholder. Without one, a placeholder matches anything except `/`. To allow slashes (e.g. a file path), use `['file' => '.+']`. ## Names and links Give every route you link to a name. In Twig: ```twig <a href="{{ path('blog_post', {slug: post.slug}) }}">{{ post.title }}</a> ``` In PHP: `$this->path('blog_post', ['slug' => $slug])` in a controller, or `$app->path(...)`. Paths come back **in the current language** (`/it/blog/…` on Italian pages); pass a third argument to target a specific one: `path('blog', {}, 'en')`. Routes without a name get one generated from the method and path, but you can't rely on it for links. ## Languages Route paths are language-neutral: you declare `/about` once, and TinyTank also serves `/it/about` for every other configured language. See [Languages](../features/languages). ## Redirects When a page moves or is renamed, keep its old address working in `config/redirects.php`: the old path and where it went. ```php return [ '/old-page' => '/new-page', // 301, moved for good '/it/vecchia' => '/it/nuova', // each language's path as it is '/summer-sale' => ['to' => '/offers', 'status' => 302], // temporary (also 307, 308) '/docs' => 'https://docs.example.com', // another site ]; ``` * They're answered **first**, before languages and routes, so the old path doesn't need to exist. * The query string is kept (`/old-page?ref=x` → `/new-page?ref=x`), and `/old-page/` is the same as `/old-page`. * A redirect can't point at another one: when `/a` went to `/b` and `/b` then moved to `/c`, point both at `/c`, so visitors and search engines take a single step. A mistake (a path without `/`, a chain, a status other than 301, 302, 307 or 308) stops the site with a message naming the entry. * `bin/console check` (and so `deploy`) reports an old path that still has a page, which the redirect would hide, and a target of this site that doesn't answer. * A [static build](../static-site-generator/hosts) writes them into the host's redirects (`_redirects` on Cloudflare). A translated page's own URL (`slug:` in its front matter) is redirected from its folder path by itself; the map is for addresses that no longer exist anywhere. ## Responses to unknown routes * An unknown path gets a **404**, a wrong method a **405** with an `Allow` header. Both render `templates/_error.twig`, or plain text for Datastar requests. * In production, an exception becomes a **500** (logged, never shown); in debug mode you get Symfony's exception page. ## Compiled in production Without `APP_DEBUG`, the router is compiled into `var/cache/routes.*.php` on first use or by `bin/console deploy`. Run `deploy` (or `cache:clear`) after changing routes in production. ## The built-in route TinyTank registers one route itself: `/datastar`, the endpoint behind `datastar.get(…)` and friends (see [Datastar](./datastar)). Don't reuse that path. --- --- url: https://docs.tinytank.dev/1.x/basics/controllers.md --- # Controllers Controllers live in `src/Controller/` and extend `TinyTank\Controller`: ```php <?php declare(strict_types=1); namespace App\Controller; use TinyTank\Controller; use Symfony\Component\HttpFoundation\Response; final class BlogController extends Controller { public function show(string $slug): string|Response { $post = $this->app->posts()->slug($slug)->one(); if ($post === null) { return $this->notFound($this->t('Post not found.')); } return $this->render('blog/post.twig', ['post' => $post]); } } ``` Each request creates a new controller, with the kernel as its only constructor argument (`$this->app`). Extending `TinyTank\Controller` is optional, but it gives you the helpers below. ## What an action returns * **A string**: sent as an HTML page (`200`, `text/html`). * **Any Symfony `Response`**: JSON, redirects, files, streamed responses, custom status codes. ```php use Symfony\Component\HttpFoundation\RedirectResponse; return new RedirectResponse($this->path('blog'), 301); ``` Successful GET pages automatically get an ETag and `Cache-Control: public, no-cache`, so repeat visits are answered with a `304`. A `304` saves sending the page again, not making it: the action still runs, and the ETag is computed from what it rendered. ## Helpers | Method | What it does | |---|---| | `render($template, $vars)` | Renders a Twig template to a string | | `stream($template, $vars)` | Renders a template as a [Datastar](./datastar) response | | `json($data, $status = 200)` | A `JsonResponse` | | `notFound($message)` | The 404 error page | | `path($name, $params, $language)` | URL path of a named route, in the current language | | `t($message, $params)` | Translates a UI text ([Languages](../features/languages)) | | `get($id)` | A service from the [container](../extending/bootstrap) | | `request()` | The current Symfony `Request` | | `signals()` | The request's Datastar signals, read with their type ([Reading signals](./datastar#reading-signals)) | ## The kernel `$this->app` is the `TinyTank\Kernel`. Its most useful parts: | Property / method | | |---|---| | `$app->seo` | Page metadata: title, description, Open Graph, JSON-LD ([SEO](../features/seo)) | | `$app->site` | Site name, URL, languages and the current language | | `$app->posts()`, `$app->pages()`, `$app->collection('name')` | Queries over posts, pages and collection items: `->where()`, `->orderBy()`, `->one()`, `->all()`… ([Querying content](./querying)) | | `$app->blog` | The posts' source, for what queries don't do: `uri()`, `translations()`, `asset()` | | `$app->container` | Services registered in `config/bootstrap.php` | | `$app->twig` | The Twig environment | | `$app->debug` | Whether debug mode is on | | `$app->error($status, $message)` | An error page with any status | The full list is in the [PHP API reference](../reference/php). ## Closures For tiny pages, a closure in `config/routes.php` is enough: ```php $app->get('/healthz', static fn () => new Response('ok', 200, ['Content-Type' => 'text/plain']), 'health'); ``` Closures receive route parameters as named arguments like controller methods do; use `$app` from the surrounding function to render templates. --- --- url: https://docs.tinytank.dev/1.x/basics/templates.md --- # Templates Templates are [Twig](https://twig.symfony.com) files in `templates/`. In production they're compiled to PHP classes in `var/cache/twig` (by `deploy` or on first use). ## The layout `templates/_layout.twig` is the page shell. Two parts of it matter to TinyTank: ```twig <html lang="{{ site.language }}"> <head> {{ theme_script() }} {# first: light/dark before anything is painted #} {% block seo %}{% endblock %} {# pages can set metadata here… #} {{ seo_tags() }} {# …printed once: title, description, Open Graph, hreflang, JSON-LD #} {{ public_config() }} {# config values allowlisted for JavaScript #} {{ vite('resources/js/app.js', page_scripts ?? []) }} {# plus the page's own bundles #} </head> ``` A page sets its metadata either in its controller (`$this->app->seo->title(…)`) or in its template, in the `seo` block that renders before the tags are printed: ```twig {% extends '_layout.twig' %} {% block seo %}{% do seo.title('About').description('Who we are.') %}{% endblock %} ``` ## What TinyTank adds to Twig | Name | Kind | Example | |---|---|---| | `path(name, params, language)` | function | `{{ path('blog_post', {slug: post.slug}) }}` | | `t` | filter | `{{ 'Load more'\|t }}`, `{{ '{n} posts'\|t({n: 3}) }}` | | `t(message, params)` | function | `{{ t('Blog') }}` | | `vite(entry, …)` | function | `{{ vite('resources/js/app.js', page_scripts ?? []) }}` | | `public_config()` | function | config values allowlisted for JavaScript | | `vite_preload(source, …)` | function | `<link rel="preload">` for a built font or image | | `theme_script()` | function | the light/dark script for the top of `<head>` | | `content(item)` | function | a post, page or item's HTML with its [components](../content/components) rendered: `{{ content(post) }}` | | `posts()`, `pages()`, `collection(name)` | functions | content queries: `posts().tag('php').limit(3).all()` ([Querying content](./querying)) | | `seo_tags()` | function | prints the page's metadata | | `absolute_url(path)` | function | `{{ absolute_url('/blog') }}` → `https://example.com/blog` | | `language_switcher()` | function | the current page in every language | | `format_date`, `format_number`… | filters | `{{ post.date\|format_date('long', locale: site.locale) }}` ([Twig Intl](https://twig.symfony.com/doc/3.x/filters/format_date.html)) | | `site` | global | `site.name`, `site.language`, `site.locale` | | `seo` | global | `{% do seo.title('…') %}` | | `datastar` | global | `datastar.get('_partials/search')` ([Datastar](./datastar)) | | `globals` | global | your own values from `config/globals.php`: `globals.socials.github` (below) | Plus the Datastar tags `patch_elements`, `patch_signals`, `remove_elements`, `execute_script` and `location` used in partials. The [Twig reference](../reference/twig) has every signature. ## Global values Values every template needs, such as social links, a phone number or an address, go in `config/globals.php` rather than being repeated in templates (like Craft's globals): ```php <?php // config/globals.php return [ 'socials' => [ 'github' => 'https://github.com/example', 'x' => 'https://x.com/example', ], 'phone' => '+39 06 1234 5678', ]; ``` ```twig <a href="{{ globals.socials.github }}">GitHub</a> {% for name, url in globals.socials %}<a href="{{ url }}">{{ name }}</a>{% endfor %} ``` The array can be nested as deep as you like. The file is optional, and it's plain PHP: a value can come from the environment (`getenv('SHOP_URL') ?: 'https://shop.example.com'`). Controllers and commands read the same values as `$app->globals`. ::: warning Public values Whatever `globals` holds can end up in a page, so never put secrets there: they belong in `.env`. Values that change by language are better as translations (`{{ 'Opening hours'|t }}`). ::: ## Partials Files in `templates/_partials/` are fragments: included by pages, and rendered on their own by Datastar requests. The leading underscore is a convention; Datastar can render any template. ## Error pages `templates/_error.twig` renders every error (404, 405, 500) with two variables, `status` and `message`. Error pages get `noindex` automatically. ## Escaping Twig escapes everything by default. Use `|raw` only for HTML you trust; the blog's rendered post HTML is safe to print raw, because Markdown is parsed with raw HTML escaped and unsafe links removed. `content()` can be stored in a variable and printed later (`{% set body = content(post) %}`). Twig's own `block('name')` can't: it returns plain text, which `{{ }}` escapes. Print a block you rendered yourself with `|raw`, since its HTML comes from your template. ## Debug mode With `APP_DEBUG=1`, templates aren't cached and `strict_variables` is on: using an undefined variable is an error instead of an empty string. Use `??` for optional variables: `{{ signals.q ?? '' }}`. --- --- url: https://docs.tinytank.dev/1.x/basics/querying.md --- # Querying content Templates and controllers don't receive content automatically: they ask for what they need, the way Craft CMS's element queries work. Only context is always there (`site`, `seo`, `datastar`). ```twig {% set latest = posts().tag('php').limit(3).all() %} {% set result = posts().search(q).paginate(page) %} {% set faq = collection('faq').all() %} {% set ada = collection('team').slug('ada').one() %} ``` ```php $latest = $this->app->posts()->tag('php')->limit(3)->all(); $faq = $this->app->collection('faq')->all(); ``` | Function | Queries | |---|---| | `posts()` | [blog posts](../content/blog), newest first | | `pages()` | [content pages](../content/pages), by path (each page before its children) | | `collection(name)` | a [data collection](../content/collections), in its `sort` order | ## How a query works 1. **Start** with `posts()` or `collection('faq')`. 2. **Narrow** it with parameters: `.tag('php')`, `.where('featured', true)`, `.limit(5)`… 3. **Run** it: `.all()`, `.one()`, `.count()`, `.paginate(page)`, or a `for` loop. Nothing is read until the last step. A production request then reads a cached PHP array that Opcache keeps in memory, so queries are cheap. Queries are **immutable**: every parameter returns a new query and leaves the original alone. So a base query can be reused and branched safely: ```twig {% set query = posts() %} {% if tag %} {% set query = query.tag(tag) %} {% endif %} {% set result = query.paginate(page) %} {% set php = posts().tag('php') %} {{ php.count }} posts, latest: {{ php.one().title }} ``` Unlike Craft's mutable queries, there's no `clone()` to remember: `{% set query = query.tag(tag) %}` is the whole pattern. ## Parameters | Parameter | | |---|---| | `where(field, value)` | items whose field equals the value (strictly: `'1'` isn't `1`). A list of values matches any of them; on a list field (`tags`), items that contain the value | | `slug(slug)` | `where('slug', …)`; one slug or a list | | `tag(tag)` | `where('tags', …)`. An empty value or `null` doesn't filter, so a request value can go straight in | | `search(text)` | items containing the text, case-insensitive. Posts: title, summary and tags; collections: their `string` and `list` fields. Empty: no filter | | `language(code)` | items in that language instead of the current one | | `orderBy('field [asc\|desc], …')` | replaces the default order: `'title'`, `'date desc'`, `'order, name'`. Items without a value come last; text is compared naturally ("Item 9" before "Item 10") and case-insensitively | | `except(item)` | every item but this one (or these: a list); items or their slugs, a page's path. `posts().except(post)` for "more posts" | | `limit(n)`, `offset(n)` | a slice of the results | `where()`, `orderBy()` and `countBy()` also reach a value inside a field by its path: a page's `data` (`where('data.featured', true)`, `orderBy('data.date desc')`) or a collection's `array` field (`where('address.city', 'Rome')`). Only the field itself (`data`, `address`) is checked; a missing value counts as `null`. A field that doesn't exist is an error, not an empty result: ``` posts: no field "titel". Did you mean "title"? Fields: slug, language, title, date, updated, image, summary, tags, draft, reading_minutes. ``` ## Running a query | Method | Returns | |---|---| | `all()` | the matching items, as a list | | `one()` | the first match, or `null` | | `count()` (or `\|length`) | how many items `all()` would return | | `exists()` | whether there's at least one | | `paginate(page, perPage = null)` | one page: `{items, page, pages, per_page, total, has_more}`. Ignores `limit` and `offset`; `perPage` defaults to `blog.per_page` for posts and 20 otherwise. A page past the end has no items | | `countBy(field)` | how many matches have each value, most frequent first: `posts().countBy('tags')` → `{php: 3, guide: 1}` | | `neighbours(item, wrap = false)` | `{prev, next}`: the items before and after one in this order (filters and `orderBy` apply, `limit` doesn't), `null` at an end, or with `wrap` the other end. For "previous / next" links | | `for item in query` | loops over `all()` | Items are arrays: see the fields of [posts](../reference/php#blog) and of [collection items](../content/collections#add-items). ## Examples Previous and next project, wrapping around, and two other projects: ```twig {% set around = collection('projects').neighbours(project, wrap: true) %} <a href="{{ path('project', {slug: around.prev.slug}) }}">◂ {{ around.prev.title }}</a> {% for other in collection('projects').except(project).limit(2) %}…{% endfor %} ``` A "latest posts" box on the home page: ```twig {% for post in posts().limit(3) %} <a href="{{ path('blog_post', {slug: post.slug}) }}">{{ post.title }}</a> {% endfor %} ``` Tag buttons with counts: ```twig {% for tag, count in posts().countBy('tags') %} <button>{{ tag }} ({{ count }})</button> {% endfor %} ``` A blog page in a controller, with a 404 past the last page: ```php $result = $this->app->posts()->paginate($page); if ($page > $result['pages']) { return $this->notFound(); } return $this->render('blog/index.twig', ['result' => $result]); ``` Featured team members, alphabetically: ```twig {% for member in collection('team').where('featured', true).orderBy('name') %}…{% endfor %} ``` ## In PHP `$this->app->posts()`, `$this->app->pages()` and `$this->app->collection('faq')` return the same `TinyTank\Query`, with the same methods. With PHPStan, `posts()` and `pages()` are typed as queries of posts and pages, so `->one()` is known to return such an array or `null`. --- --- url: https://docs.tinytank.dev/1.x/basics/datastar.md --- # Datastar [Datastar](https://data-star.dev) adds interactivity with HTML attributes: it keeps state in **signals**, sends requests to the server, and patches the page with the HTML the server sends back over server-sent events. TinyTank renders that HTML with Twig, so interactive features are plain templates. The Datastar client (v1) ships with the framework, matched to its PHP SDK, and `resources/js/app.js` loads it on every page. To combine Datastar with your own JavaScript modules, see [JavaScript & Datastar](../features/javascript). ## Render a template on demand The simplest pattern: a button or input asks the server to render a partial, and Datastar swaps it into the page by element id. ```twig {# templates/index.twig #} <input data-bind:query placeholder="Search…" data-on:input__debounce.200ms="{{ datastar.get('_partials/search') }}"> <ul id="results"></ul> ``` ```twig {# templates/_partials/search.twig #} {% set query = signal('query', max: 200)|lower %} <ul id="results"> {% for fruit in ['Apple', 'Banana', 'Cherry']|filter(f => query in f|lower) %} <li>{{ fruit }}</li> {% endfor %} </ul> ``` `datastar.get('_partials/search')` prints a Datastar action (`@get("/datastar?config=…")`). On the server, TinyTank renders the partial with the browser's **signals**. If the template queues no events, its whole output is patched into the page, matched by element id. ## Reading signals Signals come from the browser, so they can be anything: text where you expect a number, a list where you expect text. Read them with their type, and you always get what you asked for, or the default: | Twig | PHP (`$this->signals()` in a controller, `$app->signals()`) | Gives | |---|---|---| | `signal('q')`, `signal('q', 'all', max: 200)` | `->string('q', 'all', max: 200)` | the text (a number becomes its text), cut to `max` characters (1000); else the default (`''`) | | `signal_int('page', 1, min: 1, max: 1000)` | `->int('page', 1, min: 1, max: 1000)` | a whole number (or its text, `"2"`), kept within `min` and `max`; else the default (`0`) | | `signal_bool('open')` | `->bool('open')` | `true`/`false` (or `"true"`, `1`…); else the default (`false`) | | `signal_enum('sort', ['new', 'old'])` | `->enum('sort', ['new', 'old'])` | one of the choices; else the default (the first choice) | A name can reach into an object: `signal('form.email')`. `->all()` and `->has('name')` give the rest. The raw `signals` variable is still there, as sent, but `signals.page ?? 1` passes on whatever the browser sent: a list, a huge number. A request whose signals aren't valid JSON gets a **400**, and one larger than 64 KB a **413**: a browser running your page never sends either. A form that Datastar posts as a form (`contentType: 'form'`) has no signals; its fields are in the request, as without JavaScript. `post`, `put`, `patch` and `delete` work the same way. A second argument passes variables to the template: ```twig <button data-on:click="{{ datastar.post('_partials/like', {fruit: 'Mango'}) }}">Like</button> ``` ::: info Signed, but readable Those variables travel in the URL, signed with `APP_SECRET`, so they can't be tampered with. They are still **readable** in the page source: never pass secrets through them. The signature covers the **HTTP method** too: a `datastar.post()` URL only works as a POST (a GET gets a 405), so a link or a browser prefetch can't trigger it, and POSTs from other sites are refused (see [Security](../security)). Anyone who can see the page can still send that POST themselves, as often as they like: a signed URL isn't a permission. Changes that need authorization, or that must happen once, belong in a [controller](./controllers) that checks them. ::: ## Events in a partial For more than one change, queue events explicitly. They're sent in template order: ::: tip ARIA states are strings `data-attr` writes `true` as a bare attribute and removes the attribute for `false`. ARIA needs the words: `data-attr:aria-expanded="String($open)"`. ::: ::: warning Queue the HTML too As soon as a partial queues an event, **only the queued events are sent**: HTML outside `patch_elements` is dropped. A partial that changes a signal *and* an element wraps the element in `{% apply patch_elements %}`. ::: ```twig {% apply patch_elements %} <p id="likes">You liked {{ fruit }}.</p> {% endapply %} {% apply patch_elements({selector: '#log', mode: 'append'}) %} <li>{{ fruit }}</li> {% endapply %} {% do patch_signals({liked: true}) %} {% do remove_elements('#old-banner') %} {% do execute_script("console.log('updated')") %} {% do location('/thanks') %} ``` `execute_script()` is blocked by the [Content Security Policy](../security#inline-scripts-from-datastar) unless you allow that exact script; patching elements and signals is usually the better choice. ## Calling your own routes For logic that belongs in PHP, point Datastar at a route and return `stream()` from the controller: ```twig <button data-on:click="{{ datastar.action('post', path('clock')) }}">What time is it?</button> <p id="clock"></p> ``` ```php // config/routes.php $app->post('/clock', ClockController::class, 'clock'); // src/Controller/ClockController.php final class ClockController extends Controller { public function __invoke(): StreamedResponse { return $this->stream('_partials/clock.twig', ['now' => date('H:i:s')]); } } ``` `stream()` renders the template with the request's signals, exactly like the template actions. In the controller, read them with their type: `$this->signals()->int('page', 1, min: 1)`. A controller can stop with an error status for the visitor: `throw new HttpError(403, 'Not allowed.')` (`TinyTank\HttpError`) answers with that status's error page, its message translated. ## CSRF POST, PUT, PATCH and DELETE requests must come from your own site. TinyTank checks the browser's `Sec-Fetch-Site` / `Origin` headers, which every browser sends with Datastar's `fetch()` requests, so there's no token to add. See [Security](../security#csrf-protection). ## Languages Datastar URLs carry the current language (`/it/datastar?…`), so partials render in the page's language: `|t`, `path()` and dates all follow it. ## From the Craft Datastar plugin | Craft Datastar plugin | TinyTank | |---|---| | `{{ datastar.get('_partials/x', {id: 1}) }}` | same (also `post`, `put`, `patch`, `delete`) | | `{% patchelements %}…{% endpatchelements %}` | `{% apply patch_elements %}…{% endapply %}` | | `{% patchelements with {mode: 'append'} %}` | `{% apply patch_elements({mode: 'append'}) %}` | | `{% patchsignals {a: 1} %}` | `{% do patch_signals({a: 1}) %}` | | `{% removeelements '#x' %}` | `{% do remove_elements('#x') %}` | | `{% executescript %}…{% endexecutescript %}` | `{% do execute_script('…') %}` | | `{% location '/x' %}` | `{% do location('/x') %}` | | `signals` variable | same | | custom controller + `Sse` trait | controller returning `$this->stream(…)` | --- --- url: https://docs.tinytank.dev/1.x/content/blog.md --- # The blog TinyTank includes a Markdown blog, meant for articles around your site's subject (the "content" part of an SEO strategy). Posts are files in `content/blog/`; there's no database and no admin. ## What you get * **`/blog`**: the newest posts, with live search and tag filters (Datastar) * **`/blog/page/2`, `/blog/page/3`…**: older posts, with numbered page links * **`/blog/<slug>`**: a post, with its own title, description, Open Graph tags and JSON-LD * **`/blog/feed.xml`**: an Atom feed of the latest posts * every published post in **`/sitemap.xml`** * all of the above **per language** when posts are [translated](./translations) The pages are built by `App\Controller\BlogController` and the templates in `templates/blog/` and `templates/_partials/blog-*.twig`. They're part of your site, so restyle or restructure them freely; the framework provides the data (`TinyTank\Blog\Blog`) and the feed/sitemap controllers. ## Where posts live Each post is a folder named after its slug, filed by publication month, with its images next to it: ``` content/blog/ 2026/ 09/ hello-tinytank/ → /blog/hello-tinytank index.md the post (default language) index.it.md its Italian translation → /it/blog/hello-tinytank cover.png → /media/blog/hello-tinytank/cover.png drafts/ next-post/ only visible with APP_DEBUG=1, never deployed index.md ``` [Writing posts](./posts) explains the front matter, images and drafts. ## Pagination `/blog` shows the newest posts; older ones are at `/blog/page/2`, `/blog/page/3`… `/blog/page/1` redirects to `/blog`, and pages past the end are a 404. Each page has its own title ("Blog · Page 2") and canonical URL. The pager in `templates/_partials/blog-pager.twig` has numbered page links with Newer / Older: each page has a URL, for search engines, visitors without JavaScript and links you share. Search and tag results have no URLs of their own, so there the pager is a **Load more** button instead (`_partials/blog-more.twig`), which appends the next matches in place. The number of posts per page is `blog.per_page` in `config/app.php`, which reads `BLOG_PER_PAGE` (default 20). Set `BLOG_PER_PAGE=1` in `.env` to try pagination with only a few posts. ## Search and tags The search box and tag buttons on `/blog` re-render `_partials/blog-results.twig` through Datastar as you type. Search matches titles, summaries and tags; it covers the posts of the current language. ## Caching In production, posts are parsed once into `var/cache/blog.php` and their files are copied to `public/media/blog/`, both by `bin/console deploy`. **Run `deploy` after publishing.** In debug mode, posts are parsed on every request, so edits show up immediately. ## Using posts elsewhere Query posts anywhere with `posts()` in Twig or `$this->app->posts()` in PHP, for example the three latest on the home page: ```twig {% for post in posts().limit(3) %} <a href="{{ path('blog_post', {slug: post.slug}) }}">{{ post.title }}</a> {% endfor %} ``` See [Querying content](../basics/querying) for every parameter, and the [PHP reference](../reference/php#blog) for the fields of a post. --- --- url: https://docs.tinytank.dev/1.x/content/posts.md --- # Writing posts ## Create a post A post is a folder in `content/blog/YYYY/MM/` named after its slug, with an `index.md` inside: ``` content/blog/2026/10/calm-websites/index.md → /blog/calm-websites ``` ```markdown --- title: Building calm websites date: 2026-10-04 summary: Why fewer moving parts make faster, friendlier sites. tags: [design, performance] image: cover.jpg --- Calm websites load fast and stay out of the way. ## Fewer moving parts ![Diagram](diagram.webp) … ``` The slug (the folder name) must be lowercase letters, digits and dashes, and unique across the whole blog. The month folder must match the post's `date`. ## Front matter | Field | Required | Description | |---|---|---| | `title` | yes | The post title | | `date` | yes | Publication date, `YYYY-MM-DD` and a real day (`2026-02-30` is an error, not March 2); must match the `YYYY/MM` folder | | `updated` | no | Last significant change; used by the feed, the sitemap and `dateModified` | | `summary` | no | Teaser and meta description; defaults to the first paragraph that contains text | | `tags` | no | A list of tags (lowercased) | | `image` | no | Share image: a file in the post folder, a `/path` in `public/`, or an `https://` URL | ## Markdown ::: tip See every element The skeleton's **style guide** at `/style-guide` shows all of them in your site's design: a handy page for a designer, and a quick check after changing styles. ::: Posts use [GitHub-flavoured Markdown](https://github.github.com/gfm/): tables, task lists, strikethrough and autolinks. Headings get anchor links. External links open in a new tab with `rel="noopener noreferrer"`. For safety, **raw HTML is escaped** and `javascript:` links are removed, so a content file can never inject scripts into the page. ### Code blocks Name the language after the opening fence, and the code is **highlighted when content compiles**: no JavaScript, nothing loaded from another site. ````md ```php echo 'Hello'; ``` ```` ```html <pre data-lang="php"><code class="language-php"><span class="hl-keyword">echo</span> <span class="hl-value">'Hello'</span>;</code></pre> ``` Languages ([tempest/highlight](https://github.com/tempestphp/highlight)): `php`, `twig`, `html`, `css`, `scss`, `js`, `ts`, `json`, `yaml`, `bash` (or `sh`), `terminal`, `sql`, `nginx`, `apache`, `dotenv`, `dockerfile`, `diff`, `markdown`, `xml`, `ini`, `http`, `graphql`, `python`, `vue`, `svelte`, `blade`, `terraform`. A block without a language, or in another one, is shown as plain text in the same markup. The colours are the site's: the skeleton styles the `hl-*` classes at the end of `resources/css/app.css` (`hl-keyword`, `hl-property`, `hl-value`, `hl-type`, `hl-number`, `hl-variable`, `hl-attribute`, `hl-comment`, `hl-addition`, `hl-deletion`…), and shows the language from `data-lang` in the corner. The theme files in `vendor/tempest/highlight/src/Themes/Css/` (GitHub, Dracula, Monokai…) use the same classes, for ideas. Inline `` `code` `` isn't highlighted. ## Images and files Put images and files next to `index.md` (subfolders are fine) and link them relatively: ```markdown ![A diagram](diagram.webp) [Download the slides](files/talk.pdf) ``` A line like `::related-posts{limit=2}` places a [content component](./components). Images get responsive AVIF/WebP versions and lose their metadata (such as a photo's GPS position) when published: see [Images](../features/images). Relative links are rewritten to `/media/blog/<slug>/…`. Allowed types: `jpg`, `jpeg`, `png`, `gif`, `webp`, `avif`, `svg`, `pdf`, `mp4`, `webm`. Other files in the folder (notes, source files) are never published. In development, files are served from the post folder. `bin/console deploy` copies the published posts' files to `public/media/blog/`, so in production the web server serves them directly, without PHP. `bin/console cache:clear` removes those copies, so development always sees the originals. ::: warning SVG files In development, SVGs are served with a policy that blocks scripts; in production the web server serves them as plain files. That's fine for your own content, but treat SVGs from others as code. ::: ## Drafts Drafts live in `content/blog/drafts/<slug>/index.md`. They need no `date`, appear (marked "draft") only with `APP_DEBUG=1`, get `noindex`, and are never deployed: not listed, not in feeds or the sitemap, their files never copied. To publish a draft, set its `date` and move the folder into its month: ```sh git mv content/blog/drafts/calm-websites content/blog/2026/10/ ``` ## Mistakes fail loudly Every mistake below stops with a message naming the file, on the page in debug mode and in `bin/console deploy`: * a Markdown file outside `YYYY/MM/<slug>/` or `drafts/<slug>/` * a slug that isn't lowercase letters, digits and dashes, or a duplicate slug * a missing `title`, or a missing or malformed `date` * a `date` that doesn't match the month folder * a linked file or `image` that doesn't exist, isn't an allowed type, or points outside the post folder with `..` * an asset file name with characters other than letters, digits, dots, dashes and underscores * `slug:` in the default language (rename the folder instead; translations may have their own), or the old `draft:` field (move the folder instead) Drafts are never parsed in production builds, so a half-written draft can't break a deploy. --- --- url: https://docs.tinytank.dev/1.x/content/translations.md --- # Translating posts A translation sits next to the original in the post folder, as `index.<code>.md`, and shares the folder's images: ``` content/blog/2026/09/hello-tinytank/ index.md → /blog/hello-tinytank (default language) index.it.md → /it/blog/hello-tinytank cover.png ``` `index.md` is always the post in the **default language** (see [Languages](../features/languages)). ## Translated slugs By default the slug is the same in every language. A translation can have its own with `slug:`: ```markdown --- title: Ciao, TinyTank slug: ciao-tinytank --- ``` The Italian post is then `/it/blog/ciao-tinytank`. The folder name stays the post's identity: it's `post.slug` in templates and what you link with, and `path('blog_post', {slug: 'hello-tinytank'})` writes the right URL for the current (or given) language. Each version's URL is its `uri` field. * The untranslated URL, `/it/blog/hello-tinytank`, redirects permanently (301) to the Italian one, so existing links keep working. * The language switcher and `hreflang` link each version to its own URL. * `slug:` is only for translations: in the default language, rename the folder instead. * Two posts with the same URL in one language are an error. ## What a translation contains A translation needs its own `title`, and usually a `summary`. Everything it omits is inherited from `index.md`: | Field | When omitted | |---|---| | `title` | required | | `slug` | the folder name (see above) | | `summary` | the first paragraph with text, of the translation | | `date`, `updated`, `image`, `tags` | inherited from `index.md` | ```markdown --- title: Ciao, TinyTank summary: Un micro framework senza database. --- TinyTank è un piccolo framework PHP… ``` ## Untranslated posts A post that isn't written in a language **doesn't exist** in that language: it isn't listed, searchable, counted in tags or put in that language's feed, and its URL is a 404. The 404 page's language switcher still links to the versions that do exist. A post can also exist only in a non-default language: just `index.it.md`, with its own `date`. ## Language-aware SEO * the language switcher on a post links to its translations; a language without one links to that language's blog instead * `hreflang` links list only the versions that exist * each language has its own feed (`/it/blog/feed.xml`), and the sitemap lists every version ## Changing the default language Because `index.md` means "the default language", switching `language` in `config/app.php` means renaming the files: the old `index.it.md` becomes `index.md`, and the old `index.md` becomes, say, `index.en.md`. A mismatch is reported as an error. So is a file for a language that isn't in `languages`. --- --- url: https://docs.tinytank.dev/1.x/content/pages.md --- # Content pages Content pages are one-off pages written in Markdown: About, Privacy, Imprint, Contact… They work like Craft's singles, nested like a structure: each page is a folder, and the folders are the URL. The skeleton has three: `privacy`, `about` and `about/credits`. ``` content/pages/ privacy/ index.md /privacy index.it.md /it/privacy about/ index.md /about (template: pages/about.twig) team.jpg /media/pages/about/team.jpg credits/ index.md /about/credits, a child of about ``` Folder names use lowercase letters, digits and dashes. Every folder under `content/pages/` is a page and needs an `index.md`. A page's images and files sit next to it, not in a subfolder, since subfolders are child pages. The home page is a route, so there's no `content/pages/index.md`. ## Front matter ```md --- title: About us (required) summary: Who we are (optional: meta description; defaults to the first paragraph) image: team.jpg (optional share image: a file in the folder, a /path or an https URL) template: pages/about.twig (optional: its own template instead of page.twig) children: {template: pages/review.twig} (optional: the template of its child pages) order: 1 (optional: for menus) updated: 2026-10-01 (optional: last significant change, for the sitemap) data: (optional: anything else the template needs) form_title: Write to us slug: chi-siamo (translations only: this language's URL segment, see below) form: contact (optional: a form from config/forms.php the page shows and receives) cdn: false (optional: never cached at the CDN, see CDN caching) unlisted: true (optional: reachable by its URL only, see below) --- Page text in Markdown. ![Our team](team.jpg) ``` `cdn: false` matters only with [CDN caching](../deployment/cdn) on: for a page that changes more often than you deploy. Your page controller applies it (the skeleton's `PageController` does). Relative links and images point at files in the page's folder, like in posts. Any other front matter key is an error that lists the allowed ones: put custom values under `data`. ## Translations `index.<language>.md` is the page in another language. It keeps the `image`, `template`, `order`, `updated` and `data` it omits, so a translation usually only needs the title and the text. A page without a version in a language doesn't exist there: 404, and the language switcher sends visitors to that language's home page. ### Translated slugs A translation can have its own URL segment with `slug:`: ```md --- title: Chi siamo slug: chi-siamo --- ``` ``` content/pages/about/index.it.md slug: chi-siamo /it/chi-siamo content/pages/about/credits/index.it.md slug: riconoscimenti /it/chi-siamo/riconoscimenti content/pages/about/history/index.it.md (no slug) /it/chi-siamo/history ``` Child pages combine their parents' translated slugs. The folder path stays the page's identity: link with `path('page', {path: 'about/credits'})`, and TinyTank writes `/about/credits` or `/it/chi-siamo/riconoscimenti` depending on the language. Each version's URL is its `uri` field. The untranslated URL (`/it/about/credits`) redirects permanently to the translated one, and the language switcher and `hreflang` link each version to its own URL. `slug:` is only for translations (in the default language, rename the folder), and two pages with the same URL in one language are an error. ## Templates Pages render with `templates/page.twig`, which gets the page as `page`: ```twig <h1>{{ page.title }}</h1> {{ content(page) }} {# the Markdown, with its components rendered #} ``` A page with `template:` in its front matter uses that template instead, with the same `page` variable. This is how a page gets its own layout while its text stays in Markdown. A contact page, for example: ```md --- title: Contact template: pages/contact.twig data: form_title: Write to us sent: Thanks, we'll answer soon. --- We read every message and usually answer within two days. ``` ```twig {# templates/pages/contact.twig #} {% extends 'page.twig' %} {% block content %} {{ parent() }} <form data-on:submit__prevent="{{ datastar.action('post', path('contact_send')) }}"> <h2>{{ page.data.form_title }}</h2> … </form> {% endblock %} ``` The form posts to a route of your own (`contact_send` in `config/routes.php`). The texts in `data` are translated with the page: `index.it.md` gives its own `data`. A section whose pages share a template, such as reviews under `/reviews`, sets it once on the parent instead of in every child: ```md --- title: Reviews template: pages/reviews.twig # the list children: {template: pages/review.twig} # each review --- ``` Its child pages without a `template:` of their own use `pages/review.twig` (its direct children only, in every language). ## Menus and child pages Menus are queries ([Querying content](../basics/querying)). The skeleton's footer: ```twig {% for item in pages().where('parent', '').where('unlisted', false).orderBy('order, title') %} <a href="{{ path('page', {path: item.path}) }}">{{ item.title }}</a> {% endfor %} ``` A page's children, as `templates/pages/about.twig` lists them: ```twig {% for child in pages().where('parent', page.path).where('unlisted', false).orderBy('order, title') %}…{% endfor %} ``` A page has these fields: | Field | | |---|---| | `path` | `about/credits`: the folder path, the page's identity in every language | | `uri` | the URL path in this language, without the language prefix: `chi-siamo/riconoscimenti` | | `slug` | the folder name: `credits` | | `parent` | the parent's path, or `''` for a top-level page | | `depth` | `1` for top-level pages, `2` for their children… | | `language`, `title`, `summary`, `image`, `template`, `children`, `order`, `updated`, `cdn`, `unlisted`, `data` | from the file and its front matter | | `reading_minutes` | minutes to read the text, at 220 words a minute (at least 1), as posts have | | `html` | the rendered Markdown | `pages()` is sorted by path, so each page comes before its children. ### Unlisted pages A page with `unlisted: true` works like any other, for whoever has its URL, but stays out of sight: a style guide for your designer (the skeleton has one, `content/pages/style-guide/`), a thank-you page, a campaign landing page, a preview for a client. * search engines are told not to index it (`<meta name="robots" content="noindex">`); * it isn't in `/sitemap.xml`; * menus skip it, because they ask for `where('unlisted', false)`, as the skeleton's do. `pages()` itself still returns it: your templates decide what to show. Translations inherit it, unless they set their own. Unlisted isn't private: anyone with the link can open the page, and it's still served like any other. ## Routes The skeleton's `config/routes.php` has the two routes pages need: ```php $app->get(Pages::ASSET_URL . '/{file}', PageAssetController::class, 'page_asset', ['file' => '.+']); $app->get('/{path}', [PageController::class, 'show'], 'page', ['path' => Pages::PATH], priority: -1); ``` The page route is a catch-all with a **negative priority**, so every other route wins wherever it's defined, and an unknown URL ends up there as a 404. `src/Controller/PageController.php` is yours to change, like the blog's controller: it finds the page by its `uri` and redirects folder paths that a translated slug replaced. If a page has the same URL as another route in any language, for example `content/pages/blog/` next to the blog route, or an Italian `slug: blog`, it could never be shown. `deploy` stops with the page and the route's name, and the skeleton's tests check it too. ## SEO and the sitemap `TinyTank\Pages\PageSeo` (applied in `PageController`) sets the title, the summary as meta description, the share image and a `WebPage` JSON-LD block, and `noindex` for an [unlisted](#unlisted-pages) page. Every other page is in `/sitemap.xml` in each language it's written in, with `updated` as `lastmod`. ## In production Pages are compiled into `var/cache/pages.php` and their files copied to `public/media/pages/` by `deploy` (the `pages` step). Run `deploy` after changing them. In debug mode, edits show up immediately. --- --- url: https://docs.tinytank.dev/1.x/content/components.md --- # Content components Components are small reusable pieces placed inside Markdown: an audio player, related posts, a newsletter box, a video. They're like Hugo's shortcodes. One line of its own in a post, a page or a collection item's body: ```md Here's the soundscape I recorded: ::audio-player{playlist="rain-at-night" autoplay=false} More text… ``` renders `templates/_components/audio-player.twig`. The skeleton has one, `related-posts`, used at the end of its first post: `::related-posts{limit=2}`. ## Syntax ```md ::name ::name{key="text" count=3 ratio=1.5 enabled=true} ``` * The line holds only the component (up to three spaces of indentation, like any block). * The name is lowercase letters, digits and dashes: the template's file name. * Arguments are `key=value` pairs separated by spaces. A value is a `"double-quoted string"` (use `\"` inside it), a number, `true` or `false`. Arguments are plain values on purpose: no Twig expressions, no variables. Content stays content, and can't run code or reach templates that weren't made to be components. Inside code (a fenced block, an indented block or `inline code`), a component line is just text, so posts can show the syntax. ## The template A component is an ordinary Twig template in `templates/_components/`. It gets its arguments as variables, plus **`entry`**, the post, page or collection item it appears in: ```twig {# templates/_components/related-posts.twig #} {% set related = posts().tag(tag ?? null).all()|filter(post => post.slug != entry.slug)|slice(0, limit ?? 3) %} {% if related %} <aside class="not-prose"> <h2>{{ 'Related posts'|t }}</h2> {% for post in related %} <a href="{{ path('blog_post', {slug: post.slug}) }}">{{ post.title }}</a> {% endfor %} </aside> {% endif %} ``` Optional arguments read with a default (`limit ?? 3`): in debug mode an undefined variable is an error. `not-prose` keeps the typography plugin's styles out of the component. Components render on every request, in the page's language, so they can use everything a template can: `path()`, queries, `|t`, Datastar. A component that needs JavaScript can load its own bundle: `{{ vite('resources/js/components/audio-player.js') }}` in its template (the browser loads it once, even if the component appears twice on a page). ## Printing content Templates print a post, page or collection item with `content()`, which renders its components: ```twig {{ content(post) }} {{ content(page) }} {{ content(item) }} ``` `post.html` is the compiled HTML with placeholders where components go: `{{ post.html|raw }}` would leave them out. In PHP, `$this->app->content($post)`. ## Errors When content is compiled, every component is checked. These stop with the file name, in the browser during development, in the tests and in `deploy`: * a component without a template (`unknown component "audio-player" … there is no templates/_components/audio-player.twig`), for example one deleted while posts still use it * an argument that isn't a string, number or boolean, an argument given twice, or `entry` as an argument * a line that starts like a component (`::` and a letter) but doesn't parse * a component in a collection's `markdown` field (they only work in the body) ## Videos: YouTube and Vimeo Two components come with the framework: ```md ::youtube{id="aqz-KE-bpKQ"} ::youtube{id="aqz-KE-bpKQ" title="Big Buck Bunny" start=90} ::vimeo{id="1084537"} ``` `id` is the 11 characters after `watch?v=` in a YouTube URL, or the number in a Vimeo URL. `title` and `start` (seconds) are optional. A wrong `id` fails the build like any component error. **Nothing is loaded from YouTube or Vimeo until the visitor presses play.** A normal embedded player contacts the video host as soon as the page opens, which sends every visitor's IP address there, even on `youtube-nocookie.com`. These components instead show: * **A poster this site serves itself.** `deploy` (the `embeds` step) downloads each video's thumbnail and title into `public/media/embeds/`, from the server, never from visitors' browsers. In development a missing poster is downloaded once, on first view. If it can't be downloaded (offline, a private video), a neutral poster is shown and the deploy carries on with a warning. * **A play button.** Datastar then gives the player its address, and only then does the video load: YouTube from `youtube-nocookie.com`, Vimeo with its do-not-track option. * **Without JavaScript,** the poster is a link to the video on youtube.com or vimeo.com. The player's host is allowed in the [Content Security Policy](../security#content-security-policy) (`frame-src`) **only on pages that show a video**. Other pages keep the strict policy. Both use `_embeds/video.twig` for their look: copy it to `templates/_embeds/video.twig` to restyle them together. ## Overriding and default components Templates are looked up in order: 1. the site's `templates/` 2. templates added by packages, with `$app->addTemplates()` (see [Writing a TinyTank package](../extending/packages)) 3. the framework's defaults, also reachable as `@tinytank/…` So a site overrides any component, from a package or the framework, by creating a file with the same name in `templates/_components/`. An override can extend the original: ```twig {# templates/_components/youtube.twig #} {% extends '@tinytank/_components/youtube.twig' %} ``` ## Allowing sources for a component A component that needs something from another host (audio from a CDN, a map's tiles) can allow it in the Content Security Policy for the page it's on, and only that page: ```twig {% do csp_allow('media-src', 'https://cdn.example.com') %} <audio src="https://cdn.example.com/rain.opus" controls></audio> ``` `csp_allow()` refuses unknown directives and malformed sources, like the site's `csp.sources`. ## In the feed Feed readers can't run components. In `/blog/feed.xml` each component becomes a link to the post ("Open the page to see this part.", translated like any UI text). --- --- url: https://docs.tinytank.dev/1.x/content/collections.md --- # Data collections Collections hold structured content beyond blog posts: an FAQ, a team, products, a catalogue of sounds. Like posts, they're plain files in `content/`, checked when they're compiled, translatable, and compiled into a cache on deploy, so no database is involved. The skeleton's home page shows one: the FAQ in `content/faq/`. ## Define a collection Collections are defined in `config/collections.php`, with the fields each item has: ```php return [ 'faq' => [ 'fields' => [ 'question' => 'string', 'order' => 'int', ], 'sort' => 'order', ], 'team' => [ 'fields' => [ 'name' => 'string', 'role' => 'string', 'photo' => '?url', 'joined' => 'date', ], 'sort' => '-joined', 'fallback' => true, ], ]; ``` Names use lowercase letters, digits and underscores (`collection('team_members')`). `blog` and `pages` are reserved. ### Field types | Type | Value | Example | |---|---|---| | `string` | non-empty text, trimmed | `name: Ada` | | `int`, `float` | a number | `order: 2`, `price: 9.5` | | `bool` | `true` or `false` | `featured: true` | | `date` | `YYYY-MM-DD` | `joined: 2024-03-01` | | `url` | a `/path` (a file in `public/`), an `https://` URL, or in an [item folder](#items-with-their-own-files) a file next to it | `photo: /images/ada.webp`, `photo: ada.jpg` | | `markdown` | Markdown text, rendered to HTML | `bio: Writes *tests*.` | | `list` | a list of plain values | `tags: [setup, php]` | | `array` | any YAML structure, unchecked | `links: {site: https://ada.dev}` | A leading `?` makes a field optional: `'?url'`. A missing optional field is `null`. ### Options | Option | Default | | |---|---|---| | `sort` | by slug | a field to sort by; `'-field'` for descending. Items without a value come last | | `fallback` | `false` | `true`: an item without a translation appears in the default language instead of being hidden | | `json` | none | `true` or a list of fields: serves them at `/data/<name>.json` for JavaScript (below) | ## Add items Each item is a file in `content/<collection>/`, named after its slug: ``` content/faq/ what-is-tinytank.md front matter = the fields, then an optional Markdown body what-is-tinytank.it.md Italian version content/team/ ada.yaml fields only ``` A Markdown item: ```md --- question: What is TinyTank? order: 1 --- A small PHP framework for sites that are mostly content… ``` The body becomes the item's `html`. Links and images in it use `/paths` or full URLs, unless the item is a folder (below). Every item also has `slug` (from the file name), `language`, `source` (its file, for error messages), `reading_minutes` (its body at 220 words a minute, at least 1) and `assets` (an item folder's files). These names, `html` and `components` can't be used as fields. ### Items with their own files An item that has images or files of its own is a folder, named after its slug, with `index.md` (or `index.yaml`) and the files next to it, like a post: ``` content/projects/ pulse-os/ index.md the item: fields in the front matter, the body below index.it.md its Italian version cover.jpg /media/collections/projects/pulse-os/cover.jpg diagram.png nightshift.md an item without files stays a single file ``` In a folder, a `url` field can name one of its files (`image: cover.jpg`), and relative links and images in the body point at them (`![The patch graph](diagram.png)`). Images get responsive AVIF/WebP versions, in the body and through `image()`: ```twig {{ image(project.image, '', {sizes: '(min-width: 1280px) 380px, 100vw'}) }} ``` Each item lists its files in `assets`. `deploy` publishes them to `public/media/collections/`; in development this route in `config/routes.php` serves them (the skeleton has it): ```php use TinyTank\Collections\AssetController as CollectionAssetController; use TinyTank\Collections\Collections; $app->get(Collections::ASSET_URL . '/{file}', CollectionAssetController::class, 'collection_asset', ['file' => '.+']); ``` A folder holds its index files and its files, no subfolders; an item is all in its folder or all single files, not both. ## Translations `<slug>.<language>.md` (or `.yaml`) is the item in another language. Like post translations, it only needs what changes: any field it omits, and the body if it has none, keep the default-language value. So a product's Italian file can hold just `name` and the description, while its price comes from the default file. An item without a translation is hidden in that language, unless the collection has `'fallback' => true`. Then it appears in the default language, with `language` set accordingly, so templates can mark it: `<li lang="{{ item.language }}">`. ## In templates and PHP Query a collection with `collection('name')`, in the current language and the configured order (see [Querying content](../basics/querying) for every parameter): ```twig {% for item in collection('faq') %} <details> <summary>{{ item.question }}</summary> {{ content(item) }} </details> {% endfor %} {% set ada = collection('team').slug('ada').one() %} {{ collection('team')|length }} people {% for member in collection('team').where('role', 'Designer').orderBy('name') %}…{% endfor %} ``` `content(item)` prints the body with its [components](./components) rendered. `markdown` fields are HTML from Markdown with raw HTML escaped, so `{{ item.bio|raw }}` is safe. In PHP it's the same query: ```php $ada = $this->app->collection('team')->slug('ada')->one(); ``` A page per item is a route of your own: ```php $app->get('/team/{slug}', [TeamController::class, 'show'], 'team_member', ['slug' => '[a-z0-9-]+']); ``` ```php public function show(string $slug): Response|string { $member = $this->app->collection('team')->slug($slug)->one(); if ($member === null) { return $this->notFound(); } $this->app->seo->title($member['name']); return $this->render('team/member.twig', ['member' => $member]); } ``` ## JSON for JavaScript A page module that needs the data (a catalogue to filter, a mixer's sounds) can fetch it. List the fields to publish: ```php 'sounds' => [ 'fields' => ['name' => 'string', 'file' => 'url', 'notes' => '?string'], 'json' => ['name', 'file'], ], ``` They're served at `/data/sounds.json` (`/it/data/sounds.json` in Italian), with `slug` and `language`: ```js const sounds = await (await fetch(document.body.dataset.soundsUrl)).json(); ``` ```twig <body data-sounds-url="{{ path('collection_json', {collection: 'sounds'}) }}"> ``` It's an allowlist: fields not listed under `json` are never served, and collections without `json` have no URL. Responses carry an ETag like pages, so a browser that already has the file gets a `304` instead. ## Errors Collections are checked when they're compiled (on every request in development, on deploy in production), and anything unexpected stops with the file name: * a field not in the definition, a missing required field, or a value of the wrong type * a file that isn't `<slug>.md` or `<slug>.yaml`, a folder without `index.md`, or a folder inside an item folder * a translation without its default-language file, or for a language that isn't configured * a folder in `content/` that isn't the blog or a defined collection (usually a typo) * a relative link in a single-file item's Markdown, or one to a file its folder doesn't have Run `ddev composer test`: the skeleton's tests compile the site's real content, so CI catches a broken file before it's deployed. --- --- url: https://docs.tinytank.dev/1.x/features/languages.md --- # Languages ## Configuring languages ```php // config/app.php 'language' => 'en', // default: no URL prefix 'languages' => [ 'en' => ['name' => 'English', 'locale' => 'en_US'], 'it' => ['name' => 'Italiano', 'locale' => 'it_IT'], // served under /it/ ], ``` * `language` is the default language. It has **no URL prefix**: `/blog`. * Every other language in `languages` is prefixed with its code: `/it/blog`. * `name` is shown in the language switcher; `locale` is used for `og:locale`, dates and plurals. An Italian-only site sets `'language' => 'it'` and lists only `it`. Adding English later puts it under `/en/…` without changing any existing URL. ## URLs | Request | Result | |---|---| | `/blog` | the default language | | `/it/blog` | Italian (routed as `/blog`) | | `/en/blog` (English is the default) | `301` redirect to `/blog` | | `/italy` | not a language prefix: routed as `/italy` | Routes are declared once, without a prefix. `path()` returns paths in the current language, and Datastar requests carry it too, so links never fall out of the visitor's language. ## The `site` object `$app->site` in PHP and `site` in Twig hold the languages and the current one: ```twig <html lang="{{ site.language }}"> {# "it" #} {{ post.date|format_date('long', locale: site.locale) }} {# "20 settembre 2026" #} ``` | | | |---|---| | `site.language` | current language code | | `site.locale` | current locale, e.g. `it_IT` | | `site.defaultLanguage` | the default language | | `site.languages` | every configured language | ## Translating texts UI texts live in `translations/<code>.php`, which returns `[text => translation]`. Write the texts in your templates' language and wrap them: ```twig {{ 'Load more'|t }} {{ '{shown} of {total} posts'|t({shown: 20, total: 45}) }} {{ t('Blog') }} ``` ```php // translations/it.php return [ 'Load more' => 'Carica altri', '{shown} of {total} posts' => '{shown} di {total, plural, one {# articolo} other {# articoli}}', ]; ``` In PHP: `$this->t('Post not found.')` in controllers, `$app->t(…)` elsewhere. Messages use [ICU MessageFormat](https://unicode-org.github.io/icu/userguide/format_parse/messages/) through `symfony/translation`, so placeholders (`{name}`) and plurals work in every language. **A missing translation shows the text itself, never another language.** On an Italian-default site with English templates, a text missing from `en.php` stays English. So the templates' own language file only needs entries whose wording differs, or plural forms. In production, translations are compiled into `var/cache/translations` by `deploy`. ## The language switcher ```twig {% for language in language_switcher() %} <a href="{{ language.url }}"{% if language.active %} aria-current="true"{% endif %}>{{ language.name }}</a> {% endfor %} ``` Each entry has `code`, `name`, `url`, `active` and `available`. The site's version is in `templates/_partials/language-switcher.twig` and shows only when there's more than one language. On pages that exist in only some languages (a post with one translation, page 3 of a blog that's shorter in Italian), controllers declare the existing versions: ```php $this->app->site->setAlternates( ['en' => '/blog/beta'], // where this page exists ['it' => '/it/blog'], // where to send the other languages instead ); ``` The switcher then marks the other languages as unavailable and links them to the fallback, and `hreflang` lists only the existing versions. ## The site's name, description and share image In `config/app.php`, each `site` value is either the same for every language or a map per language: ```php 'site' => [ 'name' => 'TinyTank', 'description' => [ 'en' => 'A database-free PHP micro framework for static-like dynamic sites.', 'it' => 'Un micro framework PHP senza database per siti dinamici veloci come quelli statici.', ], 'image' => ['en' => '/images/share.en.png', 'it' => '/images/share.it.png'], 'author' => null, ], ``` They follow the page's language everywhere: titles (`About · TinyTank`), the meta description, Open Graph, JSON-LD, the feed's title and subtitle, and `site.name` / `site.description` in templates (`$this->app->site->name()` in PHP). A language missing from a map uses the default language's value; `null` in a map means "none in this language" (for example, no share image). A map must include the default language, and only list configured languages: anything else stops the site at boot. ## What's translated UI texts, dates, error pages, blog posts, pages, collections and their URLs, the site's name and description, feeds, `<html lang>`, `og:locale` and hreflang. --- --- url: https://docs.tinytank.dev/1.x/features/seo.md --- # SEO Every page gets a `<title>`, meta description, canonical link, Open Graph and Twitter card tags, `hreflang` links and optional JSON-LD, printed once by `{{ seo_tags() }}` in the layout. ## Setting page metadata From a controller: ```php use Spatie\SchemaOrg\Schema; $seo = $this->app->seo ->title('About') ->description('Who we are.') ->image('/images/about.jpg'); $seo->schema(Schema::organization()->name('Acme')->url($seo->url('/'))); ``` Or from a template, in the `seo` block (it renders before the tags are printed): ```twig {% block seo %}{% do seo.title('About').description('Who we are.') %}{% endblock %} ``` | Setter | Effect | |---|---| | `title(?string)` | `<title>` becomes "Title · Site name"; `null` means just the site name | | `description(?string)` | meta description, `og:description`, `twitter:description` | | `canonical(string)` | canonical URL (defaults to the current path, without the query string) | | `image(?string)` | share image: a `/path` or an `https://` URL; switches to the large Twitter card | | `type(string)` | `og:type`: `website` (default) or `article` | | `article(published, modified, tags)` | `og:type=article` plus `article:*` tags | | `noindex(bool)` | keeps the page out of search engines | | `schema(Type)` | adds a JSON-LD block built with [spatie/schema-org](https://github.com/spatie/schema-org) | Site-wide defaults (name, description, default image, author) come from `site` in `config/app.php`. ## Automatic metadata * **Blog posts** are mapped from front matter by `TinyTank\Blog\PostSeo`: title, summary, image, `og:type=article` with dates and tags, and a `BlogPosting` JSON-LD block. Drafts get `noindex`. * **Content pages** with `unlisted: true` get `noindex` and stay out of the sitemap ([Unlisted pages](../content/pages#unlisted-pages)). * **Error pages** get `noindex`. * **hreflang** links list the page in every language (or only where it exists, see [Languages](./languages#the-language-switcher)), plus `x-default` for the default language. ## Sitemap, feeds and robots.txt Three framework controllers, wired in `config/routes.php`: | URL | Controller | Content | |---|---|---| | `/sitemap.xml` | `TinyTank\Seo\SitemapController` | every static GET page in every language, plus every published post version | | `/blog/feed.xml` | `TinyTank\Blog\FeedController` | Atom feed of the 20 latest posts in the current language (`/it/blog/feed.xml`…) | | `/robots.txt` | `TinyTank\Seo\RobotsController` | allows everything and points to the sitemap | "Static" pages are routes without placeholders or a file extension. Drafts and untranslated posts never appear. ## Absolute URLs come from `APP_URL` Canonical URLs, `og:url`, `og:image`, the sitemap and the feeds use `APP_URL`, **never the request's `Host` header**. Pages are publicly cacheable, so a forged `Host` must not end up in a cached page. Set `APP_URL` correctly on every server. JSON-LD is encoded so that a `</script>` in any value can't break out of the tag. --- --- url: https://docs.tinytank.dev/1.x/features/frontend.md --- # Frontend & Vite Assets are built by [Vite](https://vite.dev) with [Tailwind CSS](https://tailwindcss.com). Sources live in `resources/`: ``` resources/ css/app.css Tailwind, plus the typography plugin for blog posts js/app.js loaded on every page: the CSS and the Datastar client js/pages/*.js one bundle per page or feature (see JavaScript & Datastar) icons/*.svg your own icons, used as icon-[app--<name>] (see Fonts & icons) ``` The Datastar client itself ships with the framework, matched to its PHP SDK, and is imported as `'datastar'`. It's MIT-licensed: its license notice is kept in your built JavaScript, and the full text is in the skeleton's `public/third-party-licenses.txt`. ## Development ```sh ddev npm run dev ``` The dev server runs on port 5173 (exposed by DDEV at `https://<project>.ddev.site:5173`). While it runs, pages load assets from it, and: | You change | What happens | |---|---| | CSS | styles update in place, no reload | | JavaScript | the page reloads (unless the module handles hot updates itself) | | a Twig template, a Markdown post, a translation file | the page reloads | This only happens with `APP_DEBUG=1`. Vite writes its URL to `var/vite.hot` while it runs, and PHP reads it in debug mode only. If Vite was killed and pages still point at port 5173, delete `var/vite.hot`. ## Production build ```sh npm run build ``` This writes hashed files and source maps to `public/build/`, plus a manifest that `{{ vite('resources/js/app.js') }}` reads to print the right `<link>` and `<script>` tags. URLs inside the bundles (fonts and images referenced from CSS) start with `/build/`, as they're served from there. `bin/console deploy --assets` runs the build for you. ## `vite.config.js` Your config only lists plugins. TinyTank's part (entry points, the `datastar` and `tinytank` import aliases, build output, manifest, the DDEV dev server, page reloads, the `VITE_PUBLIC_` env prefix) is a framework plugin: ```js import { defineConfig } from 'vite'; import tailwindcss from '@tailwindcss/vite'; import tinytank from './vendor/tinytank/framework/resources/vite/tinytank.js'; export default defineConfig({ plugins: [ tailwindcss(), tinytank(), ], }); ``` Options: `input` (entry points; default `resources/js/app.js` plus every `resources/js/pages/*.js`) and `reload` (extra file patterns that reload the page). Anything you set in `vite.config.js` overrides the plugin's defaults. ## Several entry points To keep heavy JavaScript off pages that don't need it, give a page its own bundle: create `resources/js/pages/mixer.js` (picked up automatically) and list it in the page's template: ```twig {% set page_scripts = ['resources/js/pages/mixer.js'] %} ``` The layout prints it after `app.js` with `{{ vite('resources/js/app.js', page_scripts ?? []) }}`; `vite()` accepts entries and lists of entries, and prints shared chunks once. See [JavaScript & Datastar](javascript) for how such a module works with Datastar. ## Accessibility basics The skeleton comes with a skip link, visible keyboard focus and reduced-motion handling, and every page is checked for accessibility in both themes on every push. See the [Accessibility](../accessibility/) section: what's built in, how to check before you push, and how to fix contrast. ## Environment variables in JavaScript Only variables prefixed `VITE_PUBLIC_` are ever inlined into the bundle (`import.meta.env.VITE_PUBLIC_…`). Everything else, including `APP_SECRET`, stays on the server. For values from `config/app.php`, use the `public` allowlist and `publicConfig()` (see [JavaScript & Datastar](javascript#publicconfig)). --- --- url: https://docs.tinytank.dev/1.x/features/javascript.md --- # JavaScript & Datastar Most interactivity in a TinyTank site needs no JavaScript of your own: [Datastar](../basics/datastar) attributes keep state in signals and talk to the server. Some features need real code, though: audio, canvas, maps, drag and drop. For those, TinyTank uses one pattern: * **Datastar drives the UI.** Buttons, sliders and what's visible are `data-*` attributes bound to signals, declared in the template. * **A plain JavaScript module does the heavy work.** It reads signals and reacts to their changes, and writes its results back as signals. It never touches the buttons and sliders itself. * **Each page gets its own bundle**, so that code only loads where it's used. The skeleton's home page has a working example: a Web Audio tone with a play button and a volume slider that's remembered across reloads (`templates/index.twig` and `resources/js/pages/home.js`). ## A page bundle Create a file in `resources/js/pages/`. Every file there is an entry point; you don't need to change any config: ```js // resources/js/pages/mixer.js import { effect, getPath, mergePatch } from 'datastar'; import { persist, ready } from 'tinytank'; await ready; // Datastar has applied the page's data-signals persist(['_mixer.volume']); // remembered in localStorage effect(() => { // Runs now and again whenever a signal read here changes. engine.setVolume(getPath('_mixer.volume')); }); engine.onLoaded = () => mergePatch({ _mixer: { loading: false } }); // back to the UI ``` Then load it from the page's template: ```twig {% extends '_layout.twig' %} {% set page_scripts = ['resources/js/pages/mixer.js'] %} {% block content %} <div data-signals="{_mixer: {volume: 0.5, loading: true}}"> <input type="range" min="0" max="1" step="0.01" data-bind:_mixer.volume> <p data-show="$_mixer.loading">Loading…</p> </div> {% endblock %} ``` The layout adds `page_scripts` after `app.js` (`{{ vite('resources/js/app.js', page_scripts ?? []) }}`). A controller can pass `page_scripts` to `render()` instead. `resources/js/app.js` holds what every page needs (the CSS and the Datastar client). Keep it small. ::: tip Signals that start with `_` Datastar sends every signal with each backend request, except those starting with `_`. Use a `_` prefix for state that only matters in the browser, such as a volume or an open panel. ::: ## Imports The TinyTank Vite plugin sets up two aliases: | Import | What it is | |---|---| | `'datastar'` | The Datastar client, shipped with the framework so it matches the PHP SDK. Every bundle shares one instance, and with it the same signals | | `'tinytank'` | TinyTank's browser helpers, below | The useful part of the Datastar API for modules: | Function | | |---|---| | `getPath('a.b')` | a signal's current value | | `mergePatch({a: {b: 1}})` | set signals (creates them if missing) | | `effect(fn)` | runs `fn` now and whenever a signal it read changes; returns a function that stops it | | `filtered({include: /regex/})` | the signals whose dotted path matches, as an object | ## `ready` ```js import { ready } from 'tinytank'; await ready; ``` Modules run **before** Datastar has read the page's `data-signals`. Without `await ready`, a signal the HTML declares reads as `undefined`, and a value you write is overwritten by the HTML's default a moment later. `ready` resolves on Datastar's `datastar-ready` event. ## `persist(signals, options)` ```js persist(['_mixer.volume', 'theme']); // these signals and everything under them persist(/^_mixer\./, { key: 'mixer' }); // or a pattern on the dotted path ``` Restores the signals from `localStorage` over the page's defaults, then saves every change. Only the listed signals are read back, whatever the storage holds. Options: `key` (default `'tinytank'`; give each module its own) and `storage` (default `localStorage`; `sessionStorage` works too). If storage is unavailable (private mode, quota), the page simply starts from its defaults. Datastar's own persistence is part of Datastar Pro; this helper covers the common case without it. ## `theme()` Applies the light / dark / system choice held in the `_theme` signal and saves it. The skeleton calls it in `app.js`; see [Dark & light theme](theme). ## `publicConfig()` Sometimes the browser needs a value from the server, such as the CDN address for media files. List it under `public` in `config/app.php`: ```php 'public' => [ 'media_url' => getenv('MEDIA_URL') ?: '/media', ], ``` The layout prints it with `{{ public_config() }}` as a JSON data block, and modules read it: ```js import { publicConfig } from 'tinytank'; const { media_url } = publicConfig(); ``` It's an allowlist: nothing else from the config reaches the page. Everything under `public` is readable by anyone, so never put secrets or private URLs there. TinyTank refuses to boot if a value contains `APP_SECRET`. The values are the same for every visitor, so pages stay cacheable, and a JSON data block isn't executed, so it needs no Content Security Policy entry. For values known at build time there's also `import.meta.env.VITE_PUBLIC_…` (see [Frontend & Vite](frontend#environment-variables-in-javascript)). --- --- url: https://docs.tinytank.dev/1.x/features/theme.md --- # Dark & light theme The skeleton ships with a light, dark and system theme: * **System by default.** The site follows the visitor's device setting, and switches when the device does (many phones change at sunset). * **A choice that sticks.** The sun / moon / screen toggle in the header overrides it, and the choice is remembered in the browser. * **No flash.** The right colours are there from the first frame, also when the choice differs from the system. * **Works without JavaScript.** The site still follows the system setting; only the toggle is hidden. Everything happens in the browser, so every visitor gets the same HTML and pages stay cacheable. ## How it works | Part | Where | What it does | |---|---|---| | `{{ theme_script() }}` | first in `<head>` (`templates/_layout.twig`) | a tiny inline script: reads the saved choice (or the system setting) and sets `<html data-theme="light">` or `"dark"` before anything is painted | | `_theme` signal | `templates/_partials/theme-switcher.twig` | `'light'`, `'dark'` or `'system'`, bound to three radio buttons | | `theme()` | `resources/js/app.js` | applies the signal to `data-theme`, saves it, and follows the system in `'system'` mode | | colour tokens | `resources/css/app.css` | every colour with its light and dark value | The script and `theme()` live in the framework; the tokens and the toggle are yours to restyle. ## Colour tokens Templates use named colours instead of fixed ones, so the whole site switches together: ```html <body class="bg-page text-ink"> <p class="text-muted">…</p> <button class="bg-primary text-on-primary hover:bg-primary-hover">…</button> ``` Each token is defined once in `resources/css/app.css` with both values, using CSS `light-dark()`: ```css @theme { --color-page: light-dark(var(--color-stone-50), var(--color-stone-950)); --color-ink: light-dark(var(--color-stone-800), var(--color-stone-200)); /* … */ } ``` | Token | Used for | |---|---| | `page`, `surface` | page background; header, inputs | | `ink`, `strong`, `muted`, `subtle` | body text; emphasis and hovers; secondary text; meta text | | `line`, `line-strong` | dividers; control borders | | `chip` | tags, hover backgrounds | | `primary`, `primary-hover`, `on-primary` | buttons and the text on them | | `success`, `warning`, `warning-soft` | status text and badges | To restyle the site, change the values; to add a colour, add a token. Form controls and scrollbars follow the theme too (`color-scheme`). ## The `dark:` variant For the few places a token doesn't fit, Tailwind's `dark:` variant follows the chosen theme (and the system setting when there's no JavaScript): ```html <div class="prose prose-stone dark:prose-invert">…</div> ``` ## Your own controls Any control bound to `_theme` works, for example a select: ```html <select data-bind:_theme> <option value="system">System</option> <option value="light">Light</option> <option value="dark">Dark</option> </select> ``` In JavaScript, set it like any signal: `mergePatch({ _theme: 'dark' })`. A two-way switch, for a site that only offers light and dark: ```html <button type="button" role="switch" aria-label="Light theme" data-attr:aria-checked="String($_theme === 'light')" data-on:click="$_theme = $_theme === 'light' ? 'dark' : 'light'">…</button> ``` `String(…)`: ARIA states are the words `"true"` and `"false"`, while `data-attr` writes a boolean as a bare attribute (`aria-checked=""`) or removes it. ## A default other than the system Visitors who haven't chosen get their system's setting. A site designed dark first (or light first) sets its own default in `config/app.php`: ```php 'theme' => ['default' => 'dark'], // 'system' (the default), 'light' or 'dark' ``` `{{ theme_script() }}` then uses it before the first paint (its CSP hash follows), and the layout's signal default matches it: `data-signals="{_theme: 'dark'}"`. A saved choice still wins. ## Content Security Policy The script in `<head>` is the same on every page, so a policy can allow it by its hash instead of allowing all inline scripts. `TinyTank\Theme::hash()` returns it, ready for `script-src`. --- --- url: https://docs.tinytank.dev/1.x/features/fonts-icons.md --- # Fonts & icons Fonts and icons are part of your build, served from your own site like the CSS. No requests go to Google Fonts or icon CDNs, so: * **Privacy:** visitors' IP addresses aren't sent to a third party (an issue under GDPR). * **Speed and reliability:** no extra connections, and pages work offline or behind strict networks. * **Security:** a strict Content Security Policy doesn't need to allow outside hosts. ## Fonts The skeleton uses [Inter](https://rsms.me/inter/), installed from [Fontsource](https://fontsource.org) and imported in `resources/css/app.css`: ```css @import "@fontsource-variable/inter/wght.css"; @theme { --font-sans: "Inter Variable", ui-sans-serif, system-ui, sans-serif; } ``` Vite copies the font files into `public/build/assets/` with hashed names, so they can be cached forever. A variable font holds every weight in one file per script (Latin, Cyrillic, Greek…), and browsers download only the scripts a page actually uses. ### Preloading The browser only discovers a font once the CSS has been parsed. The layout tells it earlier, so text appears in the right font sooner: ```twig {{ vite_preload('node_modules/@fontsource-variable/inter/files/inter-latin-wght-normal.woff2') }} ``` Preload only what nearly every page uses (usually one file: the main script, regular style). The path is the file's source path, as Vite's manifest lists it. Nothing is printed while the dev server runs. Font files always stay files: Vite inlines small assets as `data:` URLs, but never fonts, since the Content Security Policy only allows fonts from the site itself (some subsets weigh under 4 KB). ### Using another font ```sh npm i -D @fontsource-variable/<font> # or @fontsource/<font> for fonts without a variable version ``` Change the `@import`, the font name in `--font-sans` (or add a token like `--font-display` for headings, used as `font-display`), and the `vite_preload()` path. Search fonts at [fontsource.org](https://fontsource.org). For a font that isn't on Fontsource, put the `.woff2` files in `resources/fonts/` and declare it: ```css @font-face { font-family: "Brand"; src: url("../fonts/brand.woff2") format("woff2"); font-weight: 100 900; font-display: swap; } ``` Vite bundles it the same way: `{{ vite_preload('resources/fonts/brand.woff2') }}`. To use no web font at all, remove the `@import` and the preload: `--font-sans` falls back to the system font. ## Icons Icons come from [Iconify](https://iconify.design) through its Tailwind plugin. An icon is a class: ```html <span class="icon-[lucide--sun] size-5" aria-hidden="true"></span> ``` * **Only the icons you use are built.** Tailwind finds the class names in your templates and adds just those icons to the CSS, as small SVGs. An icon font, by comparison, ships every icon: Material Symbols is about 3 MB. * **They take the text colour** (`currentColor`): `text-muted`, `hover:text-strong`, `dark:` all work. * **Size them** with `size-*` (or `w-*`/`h-*`); the default is 1em. ### Icon sets [Lucide](https://lucide.dev) is installed. Browse 200+ sets at [icon-sets.iconify.design](https://icon-sets.iconify.design) and install the ones you need: ```sh npm i -D @iconify-json/material-symbols ``` ```html <span class="icon-[material-symbols--play-arrow-rounded]"></span> ``` The class name is `icon-[<set>--<icon>]`. ::: warning Write the full class name Tailwind only sees class names that appear complete in your files. `icon-[lucide--{{ name }}]` isn't found; keep the whole name in the template (for example in a map, as `templates/_partials/theme-switcher.twig` does). ::: ### Your own icons Put SVG files in `resources/icons/` and use them as `icon-[app--<file name>]`; the skeleton's logo is `resources/icons/tinytank.svg`, used as `icon-[app--tinytank]`. Draw them on a square canvas, with `currentColor` (or a single colour) for strokes and fills. While the dev server runs, Vite restarts by itself when you add or change one. ### Licenses Fonts and icons are other people's work, distributed with your site under their licenses. The skeleton credits them in two places, as their licenses ask: a short `/*! … */` notice in `resources/css/app.css` (kept in the built CSS), and the full texts in `public/third-party-licenses.txt`, served at `/third-party-licenses.txt`. When you switch font or add an icon set, add its notice and license there; `tests/LicensesTest.php` checks the ones the skeleton ships. Fontsource packages include their font's license in `node_modules/@fontsource…/LICENSE`, and Iconify's `info.json` names each icon set's license. ### Accessibility An icon next to text is decoration: add `aria-hidden="true"`. An icon-only button needs a text label, for example a visually hidden one: ```html <button> <span class="icon-[lucide--x] size-4" aria-hidden="true"></span> <span class="sr-only">Close</span> </button> ``` --- --- url: https://docs.tinytank.dev/1.x/features/images.md --- # Images Images in posts and pages are prepared for the web automatically: smaller modern versions for every screen, and **no hidden metadata**. You add a photo to a post's folder, and TinyTank does the rest. ## What a visitor gets ```md ![Our team](team.jpg) ``` becomes: ```html <picture> <source type="image/avif" srcset="/media/blog/x/team.jpg.480w.avif 480w, …960w.avif 960w, …1440w.avif 1440w" sizes="…"> <source type="image/webp" srcset="/media/blog/x/team.jpg.480w.webp 480w, …"> <img src="/media/blog/x/team.jpg" alt="Our team" width="1600" height="1067" loading="lazy" decoding="async"> </picture> ``` * **The right size for the screen:** each image comes in widths of 480, 960 and 1440 pixels (only those smaller than the original, plus the original's own width). The browser picks what fits. * **Modern formats:** AVIF where the server can write it, then WebP, with the original for very old browsers. A photo is typically 50 to 80% lighter. * **No jumping layout:** `width` and `height` are always set, so the page keeps its shape while images load. * **Lazy loading:** images further down load as you scroll. It works for JPEG, PNG, WebP and AVIF. SVG (scalable already) and GIF (often animated) are served as they are. ## Privacy: no metadata Photos from phones and cameras carry **metadata** (EXIF): very often the **GPS position** where they were taken, plus the device and the time. Published as they are, anyone could download the image and read where you were. TinyTank re-saves every published image without metadata, the original included (JPEGs at quality 90, visually identical), and turns photos the right way up while doing so. The versions it makes have no metadata either. This happens in development too, so what you see is what's published. ## In templates Template images, such as a post's cover, use `image()`: ```twig {{ image(post.image, '', {loading: 'eager', fetchpriority: 'high', class: 'mb-8 w-full rounded-lg'}) }} ``` | Option | | |---|---| | `preset` | a preset from `config/app.php` (see [Presets](#presets)): its widths, sizes and shape | | `loading` | `'lazy'` (default) or `'eager'`, for an image visible as soon as the page opens | | `sizes` | how wide the image is shown, if not the configured default | | anything else | an attribute of the `<img>`: `class`, `fetchpriority`, `title`… | An image that isn't a post's or page's file (an `https://` URL, a file in `public/`) gets a plain `<img>` with the same attributes. ## Presets Different places need different images: a full-width hero wants large versions, a thumbnail small ones, a card grid the same shape for every card. Presets, like Craft's image transforms, name those settings in `config/app.php`: ```php 'images' => [ 'widths' => [480, 960, 1440], 'sizes' => '(min-width: 48rem) 48rem, 100vw', 'presets' => [ 'hero' => ['widths' => [1280, 1920, 2560], 'sizes' => '100vw'], 'card' => ['widths' => [400, 800], 'ratio' => '16:9'], 'avatar' => ['widths' => [96, 192], 'ratio' => '1:1', 'position' => 'top', 'sizes' => '6rem'], 'logo' => ['widths' => [200, 400], 'ratio' => '2:1', 'mode' => 'letterbox', 'background' => '#ffffff'], ], ], ``` ```twig {{ image(page.image, '', {preset: 'hero', loading: 'eager', fetchpriority: 'high'}) }} {{ image(member.photo, member.name, {preset: 'avatar'}) }} ``` | Option | Default | | |---|---|---| | `widths` | `images.widths` | the versions to make | | `sizes` | `images.sizes` | how wide the image is shown; `image()`'s `sizes` overrides it | | `ratio` | none: the image keeps its shape | width:height, e.g. `'16:9'` or `'1:1'` | | `mode` | `crop` | how to reach the ratio (below) | | `position` | `center` | for `crop`: what stays: `top`, `bottom-right`, `left`… | | `background` | `transparent` | for `letterbox`: the padding colour, e.g. `'#ffffff'` | Every option is optional, so a preset only says what differs from the defaults: `'square' => ['ratio' => '1:1']` crops every image to a square from the centre, at the default widths. `mode`, `position` and `background` need a `ratio`. | `mode` | What it does | |---|---| | `crop` | fills the ratio exactly, cutting what's outside; `position` picks what stays | | `fit` | the whole image within the ratio's box, keeping its own shape | | `letterbox` | the whole image within the box, padded to the exact ratio with `background` | | `stretch` | distorted to the box | **Ratio instead of height:** a Craft transform makes one image (`width: 1200, height: 630`); a preset makes several widths, so the shape is a ratio (`'1200:630'`), and each width gets the matching height. Images are never enlarged: widths larger than the image allows are left out, and the largest possible version is always made. A preset with a shape uses its largest WebP version as the `<img>` fallback, since the original isn't that shape. Only the widths and shapes of the configured presets exist. A URL asking for any other version is a 404, so nobody can make the server encode endless versions. `deploy` makes every preset's versions of every image (templates choose presets as pages render), and an unknown preset name in a template is an error. ## Configuration ```php // config/app.php 'images' => [ 'widths' => [480, 960, 1440], 'sizes' => '(min-width: 48rem) 48rem, 100vw', // the content column's width // 'formats' => ['avif', 'webp'], // default: both, where the server supports them // 'quality' => ['avif' => 50, 'webp' => 75, 'jpeg' => 90], ], ``` `sizes` tells the browser how wide images are shown, so it can choose a version before the CSS is loaded. The skeleton's content column is at most `48rem` wide; change it if your layout differs. ## When images are made * **On deploy**, when publishing post and page files: every image's versions and its original without metadata. Encoding is kept in `var/images/`, named after the image's content, so a later deploy only encodes new or changed images. **Keep `var/images/` between deploys** on the server. * **In development**, each version is made the first time it's requested. ## Server requirements PHP's **GD** or **Imagick** extension with WebP support, which nearly every host has. AVIF is used when the extension supports it too (GD with libavif, or Imagick); otherwise images get WebP only. [Intervention Image](https://image.intervention.io) does the work, with Imagick when it's installed. Without either, the site still runs and shows images as they are, in a plain `<img>`; but `deploy` can't publish the content's images, since it can't remove their metadata. `bin/console check` says so before you deploy. --- --- url: https://docs.tinytank.dev/1.x/features/forms.md --- # Forms TinyTank handles forms without a database: a visitor fills one in, it's checked, and it's **emailed**. Nothing is stored. The skeleton's Contact page (`/contact`, `/it/contatti`) is a working example. ## Defining a form Forms are defined in `config/forms.php`: ```php return [ 'contact' => [ 'fields' => [ 'name' => ['type' => 'text', 'required' => true, 'max' => 100], 'email' => ['type' => 'email', 'required' => true], 'topic' => ['type' => 'choice', 'choices' => ['question', 'feedback']], 'message' => ['type' => 'textarea', 'required' => true, 'min' => 10, 'max' => 5000], ], 'to' => getenv('CONTACT_TO') ?: null, // recipients, comma-separated 'subject' => 'Message from {name}', // translated; field values as placeholders 'spam' => ['honeypot', 'timing' => 3, 'max_links' => 2, 'rate_limit' => '5/hour'], ], ]; ``` | Field type | Value | |---|---| | `text` | one line (line breaks are removed) | | `email` | a valid email address | | `textarea` | several lines | | `choice` | one of `choices` | | `checkbox` | ticked or not; `required` means it must be ticked | Options per field: `required`, `min` and `max` (characters). Control characters are stripped, and every type has a maximum length even without `max`, so nobody can send a novel. The visitor's address (the first `email` field, or `reply_to`) goes in the email's **Reply-To**: you reply directly. The message comes **from** `MAILER_FROM`, an address of your own domain, so it passes SPF, DKIM and DMARC checks. ## Validation in the page's language The messages (`This field is required.`, `Use at most {max} characters.`…) are UI texts, translated in `translations/<code>.php` like any other, so an Italian page shows Italian errors. More rules go in `config/bootstrap.php`. A rule gets the field's value and all the values, and returns an error message or `null`: ```php $app->forms->rule('contact', 'message', fn (mixed $value) => str_contains(strtolower((string) $value), 'casino') ? $app->t('No, thanks.') : null); ``` ## Sending email Email goes out with [Symfony Mailer](https://symfony.com/doc/current/mailer.html). Set in `.env`: ```sh MAILER_DSN=smtp://user:pass@smtp.example.com:587 MAILER_FROM=hello@example.com CONTACT_TO=you@example.com ``` `MAILER_DSN` takes any Symfony Mailer transport: plain SMTP, or providers such as Mailgun, Postmark or Amazon SES with their bridge package (`composer require symfony/mailgun-mailer`). **In DDEV**, `.ddev/config.yaml` points these at **Mailpit**, which catches every message: nothing is really sent, and `ddev mailpit` opens the inbox. (Run `ddev restart` after changing them.) The email lists every field. To write your own, create `templates/_emails/<form>.txt.twig` (plain text: `.txt.twig` templates aren't HTML-escaped), with `values`, `form` and `site_name`. ## The page and the template A content page shows a form with `form:` in its front matter: ```md --- title: Contact template: pages/contact.twig form: contact --- Questions or ideas? Write to us. ``` `PageController` then gives its template a `form` with the state: | | | |---|---| | `form.values.email` | what was typed (kept after an error) | | `form.errors.email` | the field's error, if any | | `form.errors._form` | a message about the whole form (too many links, too many messages) | | `form.sent` | whether it went out | The skeleton's `templates/_forms/contact.twig` is the form itself. Inside the `<form>`, `{{ form_spam('contact') }}` prints the spam checks' hidden fields. It submits with Datastar, so errors and the thank-you appear in place without a reload: ```twig <form id="contact-form" method="post" action="{{ url }}" data-on:submit__prevent="{{ datastar.action('post', url, {contentType: 'form'}) }}"> ``` **Without JavaScript** it's a normal form post: errors show the page again, and a successful send redirects to `?sent=1`, so refreshing the page can't send the message twice. The kernel's [same-origin check](../security#csrf-protection) protects it like every POST. ## Spam protection Every built-in check runs **on this server**: no captcha service, no third-party script, nothing about visitors leaves the site. | Check | How it works | What it keeps | |---|---|---| | `honeypot` | a field hidden from people (off-screen, out of the tab order, hidden from screen readers) that bots fill in | nothing | | `timing` | the form carries a token with the time it was shown, signed with `APP_SECRET`; sent within N seconds (default 3), it's a bot. After a day it has expired. On a [static site](../static-site-generator/forms#what-happens-on-the-static-site) the build signs the token: posts without it are dropped | nothing | | `max_links` | more than N links (default 2) is refused, with a message | nothing | | `rate_limit` | at most N messages per visitor (`'5/hour'`, `'20/day'`) | a keyed hash of the IP (HMAC with `APP_SECRET`, which can't be turned back into the address), in `var/state/forms/` (kept across deploys), only for the length of the window | A bot caught by the honeypot or the timing sees "sent" like everyone else, so it learns nothing. Too many links or messages get a message, since a person can act on it. The log records that a form was sent or rejected and why (`Form "contact" rejected as spam (honeypot).`), never what was in it. **Pages with a form are never cached**: the timing token makes every view different, so they're sent with `Cache-Control: no-store`. Every other page keeps its ETag and public caching. ### Adding a spam check A check implements `TinyTank\Forms\Spam\SpamCheck`: `markup()` prints what it needs inside the form, `check()` returns `null` or a `SpamResult`. Register it in `config/bootstrap.php` (or a package's `register()`) and list it in a form's `spam`: ```php $app->forms->addSpamCheck('altcha', fn (mixed $option, Form $form) => new AltchaCheck(…)); ``` Forms are checked once bootstrap has run, so a misspelled check name still stops the site at boot rather than letting spam through. A self-hosted proof-of-work challenge such as [ALTCHA](https://altcha.org) fits this privacy-first approach. Third-party captchas (Cloudflare Turnstile, hCaptcha) send visitors' IP addresses to another company: load them only when the visitor starts filling in the form, allow their hosts on that page only with `csp_allow()`, and mention them on your privacy page. ## Privacy * Submissions are **emailed, not stored**. There's no database of messages, and the [log](./logging) only says a form was sent or rejected as spam, never what was in it. * Tell visitors what happens to their details. The skeleton's form says "We use your details only to reply to you" with a link to the Privacy page, which has a paragraph about the form. ## On a static site A static build has no PHP to receive the form, but its host can: with `'static' => ['from' => …]` in the form's definition, Cloudflare checks and emails it, with the same rules and messages. See [Static Site Generator → Forms](../static-site-generator/forms). ## Testing forms `KernelTestCase::request()` takes form fields: ```php $response = $this->request($app, '/contact', 'POST', ['Sec-Fetch-Site' => 'same-origin'], parameters: [ 'email' => 'not-an-email', ]); self::assertStringContainsString('Enter a valid email address.', self::body($response)); ``` In the browser tests, wait a few seconds before submitting (`tests/e2e/contact.spec.js`): the timing check refuses forms filled in faster than a person could. --- --- url: https://docs.tinytank.dev/1.x/features/logging.md --- # Logging When something goes wrong in production, the visitor sees a polite error page and the details go to the **log**: a file on your server, and optionally an email to you. TinyTank logs with [Monolog](https://github.com/Seldaek/monolog), PHP's standard logging library, set up so the log helps you fix problems **without becoming a record of your visitors**. ## Where the log is ``` var/log/app-2026-10-06.log var/log/app-2026-10-05.log … ``` One file per day, in `var/log/` (outside `public/`, so it's never served). Files older than 14 days are deleted automatically. A log line looks like this: ``` [2026-10-06 16:04:16] app.INFO: Form "contact" sent. {"method":"POST","path":"/contact","route":"page"} [2026-10-06 16:04:16] app.ERROR: Price list unreadable {"exception":"[object] (RuntimeException(code: 0): Price list unreadable at src/Prices.php:42) [stacktrace] #0 src/Controller/PriceController.php(18): App\Prices->load() …"} {"method":"GET","path":"/prices","route":"prices"} ``` To follow it live: `tail -f var/log/app-$(date +%F).log`. ## What's logged | What | Level | |---|---| | An uncaught exception (the visitor got the 500 page) | `error` | | A PHP warning in production (`Undefined array key`…): the page still renders, but there's a bug | `error` | | A PHP notice | `warning` | | A fatal PHP error, or the error page itself failing | `critical` | | A form was sent | `info` | | A form was rejected as spam, and which check rejected it | `notice` | **Not logged:** pages that don't exist (404s), and PHP deprecations in production: they're notes for developers about future PHP versions, left to PHP's own settings (production `php.ini` ignores them). The **level** says how serious a message is, from `debug` to `emergency`. Messages below the configured level aren't written: by default `debug` in development (everything) and `info` in production. Set `LOG_LEVEL` to change it, for example `LOG_LEVEL=warning` for a quieter log. ## Privacy: what the log leaves out A log is personal data as soon as it can tell who visited, and under the GDPR personal data needs a reason to be collected, has to be protected, and can't be kept forever. Most logging setups record far more than they need. TinyTank's log is built to answer "what broke, and where?" and nothing else: * **No IP addresses.** An IP address can identify a person (the EU Court of Justice has ruled so). Web servers and many frameworks log it with every line; TinyTank doesn't. A broken page is broken for everyone, so who saw it adds nothing. * **No browser, no referrer.** The user agent and the page someone came from build a profile of a visitor; they don't help fix a bug. * **No query string.** `/search?q=…` or a link with `?email=…&token=…` can contain anything a visitor typed or was sent. Entries carry the **method, path and route name** only: enough to reproduce the problem. * **No 404s.** Bots try `/wp-login.php` all day, and people mistype addresses. A list of everything visitors typed in the address bar is noise for you and data about them. * **No form content.** The log says a form was sent, or which spam check stopped it, never what was written in it (see [Forms](./forms#privacy)). * **No function arguments in traces.** An exception's stack trace lists the functions that were running, and PHP can include the values passed to them: a password being checked, an email address being sent to. In production, TinyTank turns that off (`zend.exception_ignore_args`), so traces show where, not what. * **Deleted after 14 days.** The GDPR's *storage limitation* principle: keep data only as long as needed. Two weeks is enough to notice and fix a problem; `days` changes it. * **No third party.** Error-tracking services (Sentry, Bugsnag, Better Stack…) receive your errors, and with them whatever the errors contain, on someone else's servers, often outside the EU. TinyTank's log stays on your server, and alerts go through your own mailer. The one exception is yours to choose: [push alerts](#push-alerts) send an error's message (nothing else) to Pushover. What can still end up in it: **error messages**, which are written by whoever threw the error. A library's message may quote the value it refused (an address, a file name), and so may your own code's. They're logged as they are, because the message is what tells you what broke. So TinyTank's log describes your site, not your visitors. Your **web server's** access log is another matter: nginx and Apache record every request with its IP address unless you configure them not to (see [Servers](../deployment/servers#access-logs)). ::: tip Your own messages The same applies to what your code logs, and to the messages of the exceptions it throws. Log what happened, not who did it: `$app->logger->info('Newsletter sent to {count} subscribers', ['count' => 120])`, not the addresses; `throw new RuntimeException('The subscriber list is empty')`, not its contents. ::: ## Email alerts Knowing about a problem before your visitors write to you: ```sh # .env LOG_ALERT_TO=you@example.com # comma-separated for several ``` From then on, an `error` (or worse) is emailed to you, through the mailer forms use (`MAILER_DSN`, `MAILER_FROM`): * **With what led to it:** the email contains the error and every line logged before it in the same request, so you see the context, not just the last line. * **Once per hour per error:** if the same error happens on every request during a traffic spike, you get one email, not five hundred. A different error gets its own email. * **After the visitor has the page:** the email is sent once the response is out (PHP-FPM), so an error doesn't make the error page slower. * If the email can't be sent (wrong SMTP password, server down), the log file says so; the error itself is in the file either way. The subject reads `[Your site] ERROR: Price list unreadable`. ## Push alerts A notification on your phone instead of, or as well as, an email, through [Pushover](https://pushover.net) (a one-time licence per platform, iOS, Android or desktop, after a free trial; sending through its API costs nothing): 1. In Pushover, copy your **user key**, and create an application (**Create an Application/API Token**): its **API token**. 2. Put both in `.env`: ```sh PUSHOVER_TOKEN=… # the application's API token PUSHOVER_USER=… # your user key ``` From then on, an `error` (or worse) is pushed with your site's name as the title: * **The message only:** no trace, no earlier lines, no request details. An error's message can still quote a value (see above), so it goes to Pushover's servers: that's the choice you make by turning this on. Leave the variables empty to keep everything on your server. * **Once per hour per error,** like the emails, and **after the visitor has the page**. * Both keys or neither: one alone stops the site with a message saying so. On a [static site](../static-site-generator/forms#when-a-message-can-t-be-sent), the same two keys make the form's Worker push an alert when a message can't be sent. ## Configuration ```php // config/app.php 'log' => [ 'level' => getenv('LOG_LEVEL') ?: null, // null: debug in development, info in production 'days' => 14, // daily files to keep 'alert_to' => getenv('LOG_ALERT_TO') ?: null, 'pushover' => ['token' => getenv('PUSHOVER_TOKEN') ?: null, 'user' => getenv('PUSHOVER_USER') ?: null], // 'path' => 'php://stderr', // another file, or a stream ], ``` `path` is `var/log/app.log` by default (the date is added to the name). A stream such as `php://stderr` is for platforms that collect a process's output themselves (Docker, some PaaS); there, the platform decides how long logs are kept. On the server, `var/log/` must be **writable by PHP**. If the log can't be written (permissions, a full disk), pages keep working and PHP's own error log gets a short note instead. ## Logging from your code The logger is `$app->logger`, also in the container as `Psr\Log\LoggerInterface` (the PSR-3 standard, so any library that accepts a logger takes it): ```php $this->app->logger->warning('Price list is {days} days old', ['days' => $age]); ``` ```php use Psr\Log\LoggerInterface; $client = new SomeApiClient(logger: $app->container->get(LoggerInterface::class)); ``` `{name}` placeholders are filled from the context. Use the levels for what they mean: `info` for things worth knowing, `warning` for something odd, `error` for something broken (it sends an alert). ### Sending logs elsewhere The logger is a Monolog `Logger`, so a [package](../extending/packages) or `config/bootstrap.php` can add any Monolog handler: ```php use Monolog\Handler\SyslogHandler; $app->logger->pushHandler(new SyslogHandler('my-site')); ``` If you add an error-tracking service this way, check what it sends and where, and mention it in your privacy policy. ## Testing `KernelTestCase` gives every test its own log directory, and `$this->logged()` returns what was logged: ```php $this->request($app, '/contact', 'POST', …); self::assertStringContainsString('Form "contact" sent.', $this->logged()); self::assertStringNotContainsString('ada@example.test', $this->logged()); ``` --- --- url: https://docs.tinytank.dev/1.x/extending.md --- # Building a site on TinyTank A new site starts from the skeleton and installs the framework as a Composer package. The site adds its own routes, controllers, templates, content and commands, and **never edits the framework**. ## The rule: never edit `vendor/` Everything site-specific lives in your own files: | What | Where | |---|---| | Routes | `config/routes.php` | | Settings | `config/app.php`, `.env` | | Services, Twig extensions, deploy steps | `config/bootstrap.php` | | Controllers, commands, other classes | `src/` (namespace `App\`) | | Templates | `templates/` | | Posts | `content/` | | UI texts | `translations/` | | CSS, JS, Vite entry points | `resources/`, `vite.config.js` | | Tests | `tests/` | Framework improvements then arrive with a single command, without touching your files: ```sh composer update tinytank/framework ``` If you find yourself needing to change the framework, that's a missing extension point: open an issue or contribute it to TinyTank instead (see [Contributing](../contributing)). See [Updating TinyTank](./updating) for versions and what to check after an update. ## The extension points | Extension point | Use it for | Guide | |---|---|---| | `config/bootstrap.php` | services, Twig extensions and globals, deploy steps | [Services & bootstrap](./bootstrap) | | `$app->container` | shared objects (a mailer, an API client) | [Services & bootstrap](./bootstrap#services) | | `src/Command/` | console commands, registered automatically | [Console commands](./commands) | | `$app->addDeployStep()` | build steps in `bin/console deploy` | [Deploy steps](./deploy-steps) | | `TinyTank\Controller` | controllers with helpers | [Controllers](../basics/controllers) | | `vite.config.js` | entry points, extra Vite plugins | [Frontend & Vite](../features/frontend) | ## A typical small app TinyTank is not opinionated about your application code. A small app usually is: * the **blog**, for articles around the app's subject * one or more **custom routes and controllers**: the app itself, for instance an interactive home page driven by Datastar, plus JSON endpoints its JavaScript loads (`$this->json(…)`) * **services** for anything shared (`config/bootstrap.php`) * **commands** for build or maintenance tasks, hooked into `deploy` when they produce files the site serves ## Housekeeping when you start a site * Commit your `composer.lock` (remove it from `.gitignore` first) * Replace the Datastar demo page and the sample blog posts * Set the real site name, description, default share image and author in `config/app.php` * Choose the languages (`language`, `languages`) and fill `translations/*.php` * Prepare each server's `.env` (`APP_URL`, `APP_SECRET`, `APP_OPCACHE`…), see [Servers & Opcache](../deployment/servers) --- --- url: https://docs.tinytank.dev/1.x/extending/bootstrap.md --- # Services & bootstrap ## `config/bootstrap.php` This file is your site's extension point. It receives the kernel once per request and once per console run, **before** `config/routes.php`, so route handlers can rely on everything registered here: ```php <?php declare(strict_types=1); use TinyTank\Kernel; return static function (Kernel $app): void { // Services $app->container->set(Mailer::class, fn (Kernel $app) => new Mailer(getenv('MAILER_DSN'))); // Twig $app->twig->addExtension(new App\Twig\AppExtension()); $app->twig->addGlobal('support_email', 'help@example.com'); // Deploy $app->addDeployStep('audio', 'app:build-audio', 'Encode the sound files'); }; ``` The file is optional; delete it if your site doesn't need it. ## Services `$app->container` is a minimal [PSR-11](https://www.php-fig.org/psr/psr-11/) container: ```php // A factory: runs once, on first use, receives the kernel; the result is shared. $app->container->set(Mailer::class, fn (Kernel $app) => new Mailer(getenv('MAILER_DSN'))); // A ready-made value. $app->container->set('clock', new SystemClock()); ``` Use services wherever you have the kernel: ```php $this->get(Mailer::class) // in a controller $this->app()->container->get(Mailer::class) // in an AppCommand $app->container->get('clock') // anywhere else $app->container->has('clock') // check first ``` Asking for an unregistered service throws a `Psr\Container\NotFoundExceptionInterface`. There's no autowiring and no configuration language: just names and factories. A closure is always treated as a factory, so to store a closure itself, wrap it in a factory. ## Twig extensions Anything Twig supports can be added in bootstrap: extensions, globals, functions, filters. Plain values (links, an email address) are simpler in [`config/globals.php`](../basics/templates#global-values), under `globals`. ```php use Twig\TwigFilter; $app->twig->addFilter(new TwigFilter('initials', fn (string $name) => implode('', array_map( fn ($word) => mb_substr($word, 0, 1), explode(' ', $name), )))); ``` ```php // src/Twig/AppExtension.php namespace App\Twig; use Twig\Extension\AbstractExtension; use Twig\TwigFunction; final class AppExtension extends AbstractExtension { public function getFunctions(): array { return [new TwigFunction('year', fn () => date('Y'))]; } } ``` ## Other kernel parts The kernel exposes TinyTank's own services, which you can use (but not replace) from bootstrap: `$app->twig`, `$app->blog`, `$app->seo`, `$app->site`, `$app->router`, `$app->translations`, `$app->vite`, `$app->datastar`. See the [PHP API reference](../reference/php). --- --- url: https://docs.tinytank.dev/1.x/extending/commands.md --- # Console commands `bin/console` runs TinyTank's commands (`deploy`, `cache:clear`) plus **every command class in `src/Command/`**, registered automatically. ## Writing a command Extend `TinyTank\Console\AppCommand` to get the app through `$this->app()`: ```php <?php declare(strict_types=1); namespace App\Command; use TinyTank\Console\AppCommand; use Symfony\Component\Console\Attribute\AsCommand; use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; #[AsCommand('app:posts', 'Lists the published posts.')] final class PostsCommand extends AppCommand { protected function execute(InputInterface $input, OutputInterface $output): int { foreach ($this->app()->posts() as $post) { $output->writeln("{$post['date']} {$post['title']}"); } return Command::SUCCESS; } } ``` ```sh ddev console app:posts # or: php bin/console app:posts ``` Commands use [Symfony Console](https://symfony.com/doc/current/console.html): arguments, options, `SymfonyStyle` output and everything else work as documented there. ## How discovery works * every concrete class in `src/Command/` (and its subfolders) that extends Symfony's `Command` is registered; abstract classes and other classes are skipped * the class name must match the file (`src/Command/Audio/BuildCommand.php` → `App\Command\Audio\BuildCommand`) * commands are created **without constructor arguments**. Need the app or a service? Extend `AppCommand` and use `$this->app()`. A command with required constructor arguments is reported as an error. ## The kernel is booted lazily `$this->app()` boots the kernel the first time it's called, so `bin/console list` works even before a site is configured. Plain Symfony commands in `src/Command/` work too, if they don't need the app. `$this->root()` returns the project root. ## Running commands during deploy A command can become a step of `bin/console deploy`; see [Deploy steps](./deploy-steps). It then runs with the same production-mode kernel as the rest of the deploy. --- --- url: https://docs.tinytank.dev/1.x/extending/deploy-steps.md --- # Deploy steps `bin/console deploy` runs named steps in order. Your site can add its own: a command that builds files the site serves, a cache to warm, a notification to send. ## Built-in steps ```sh ddev console deploy --list-steps ``` | Step | What it does | |---|---| | `assets` | only with `--assets`: `npm run build` | | `check` | `bin/console check` ([Checking first](../deployment/#checking-first)): an error stops the deploy | | `composer` | `composer dump-autoload --optimize --classmap-authoritative` | | `cache` | start the new cache, aside, in `var/deploy/next/cache/` | | `routes` | compile the router | | `blog` | compile the posts and publish their files for `public/media/blog/` (images without metadata, plus their responsive versions) | | `pages` | compile the content pages, check that no route hides one, publish their files for `public/media/pages/` | | `collections` | compile the data collections, publish their item folders' files for `public/media/collections/` | | `embeds` | download the posters and titles of `::youtube` / `::vimeo` videos to `public/media/embeds/` (a failed download is a warning) | | `translations` | compile the translation catalogues | | `templates` | compile every Twig template | | `vite` | cache the Vite manifest; without it the deploy stops (every page needs it), unless the site has no `vite.config.js` | | `switch` | move the new cache and files in place of the live ones, keeping those in `var/deploy/prev/` ([Build first, switch last](../deployment/#build-first-switch-last)) | | `opcache` | refresh the web server's Opcache ([Servers & Opcache](../deployment/servers)) | | `cdn` | purge the CDN, when [CDN caching](../deployment/cdn) is on and `CDN_PURGE` is set | ## Adding a step In `config/bootstrap.php`: ```php // A console command (from src/Command/) $app->addDeployStep('audio', 'app:build-audio', 'Encode the sound files'); // A closure $app->addDeployStep('stats', function (Kernel $app, SymfonyStyle $io): ?bool { $io->writeln(sprintf(' ✔ %d posts', $app->posts()->count())); return true; // false stops the deploy }, 'Print stats', after: 'blog'); ``` ```php $app->addDeployStep( string $name, \Closure|string $step, // closure, or a console command name string $description = '', ?string $before = null, // insert before this step… ?string $after = null, // …or after this one ); ``` Without `before` or `after`, the step runs **just before `switch`**: what it writes into the new cache goes live with the rest, and a failure leaves the live site as it was. ## How steps run * a closure receives the kernel and the console output; returning `false` stops the deploy with exit code 1 * a command step runs the command; a non-zero exit code stops the deploy * app steps run with the same **production-mode** kernel as the rest of the deploy * the kernel builds the **new** cache: `$app->cacheDir` is `var/deploy/next/cache/` until `switch`, so a step writes there and its files go live with the rest. A step after `switch` sees the live site (a notification, a warm-up request); don't write into the cache from there * the `cache` step guarantees the new cache folder exists, so later steps can write into it ## Skipping steps ```sh ddev console deploy --skip=composer,opcache ``` An unknown step name in `--skip`, or a `before`/`after` pointing to an unknown step, is an error before anything changes. --- --- url: https://docs.tinytank.dev/1.x/extending/packages.md --- # Writing a TinyTank package A feature you want in several sites (an audio player component, a contact form, a newsletter integration) can live in its own Composer package. There's no plugin system to learn: a package is a normal library that a site turns on with one explicit line. ## The convention The package has a class with a static `register()` method that receives the kernel: ```php namespace Acme\AudioPlayer; use TinyTank\Kernel; final class AudioPlayer { public static function register(Kernel $app): void { // Templates: content components and partials, overridable by the site. $app->addTemplates(dirname(__DIR__) . '/templates', 'acme-audio'); // Anything else bootstrap.php can do: $app->twig->addExtension(new AudioPlayerExtension()); $app->container->set(Playlists::class, fn () => new Playlists()); $app->addDeployStep('audio', fn (Kernel $app, $io) => Playlists::build($app, $io), 'Encode the playlists', before: 'opcache'); } } ``` The site installs it and calls it from `config/bootstrap.php`: ```sh composer require acme/tinytank-audio-player ``` ```php // config/bootstrap.php return static function (Kernel $app): void { Acme\AudioPlayer\AudioPlayer::register($app); }; ``` Nothing is discovered automatically: a site's `bootstrap.php` lists everything it uses. ## Templates `$app->addTemplates($dir, $namespace)` adds the package's templates after the site's and before the framework's. With `templates/_components/audio-player.twig` in the package, posts can use `::audio-player{…}` (see [Content components](../content/components)), and a site restyles it by creating its own `templates/_components/audio-player.twig`, which can extend the original: ```twig {% extends '@acme-audio/_components/audio-player.twig' %} ``` The package's templates use Tailwind classes the site must generate: tell the site to add the package's folder to `resources/css/app.css`: ```css @source "../../vendor/acme/tinytank-audio-player/templates"; ``` ## Console commands and deploy steps The console discovers commands in the site's own `src/Command/` only. A package ships its command class, setting its name in `configure()` (`$this->setName('acme:build-audio')`) rather than with `#[AsCommand]`, because PHP attributes aren't inherited. The site then enables it with an empty subclass: ```php // src/Command/BuildAudioCommand.php namespace App\Command; final class BuildAudioCommand extends \Acme\AudioPlayer\BuildAudioCommand { } ``` A deploy step from `register()` should be a closure (`addDeployStep('audio', fn (Kernel $app, $io) => …)`), so it works whether or not the site enabled the command. ## A CDN A package can add a CDN to purge with a class implementing `TinyTank\Cdn\Purger`, given in `register()` with `$app->cdn->usePurger(…)`. See [CDN caching](../deployment/cdn#another-cdn-as-a-package). ## Dependencies Require `tinytank/framework` with the same constraint as sites (`^0.1@dev`) and keep the package's own dependencies small: every site that installs it pulls them in. --- --- url: https://docs.tinytank.dev/1.x/extending/updating.md --- # Updating TinyTank The framework is the `tinytank/framework` Composer package, so updating it never touches your site's files: ```sh ddev composer update tinytank/framework ``` Then run your checks and look at the result before deploying: ```sh ddev composer test ddev composer analyse ``` ## Versions TinyTank is in **beta (0.x)**. Releases are tagged (`v0.1.0`…) and listed, with what to change in your site, in the [CHANGELOG](https://github.com/tinytankphp/framework/blob/main/CHANGELOG.md). The skeleton requires: ```json "require": { "tinytank/framework": "^0.1@dev" }, "prefer-stable": true ``` `^0.1` means any 0.1.x release: fixes, and additions that need no change in your site. With `prefer-stable`, `composer update` installs the latest **tagged** one; `@dev` only lets maintainers work against the `main` branch (see Contributing). While TinyTank is 0.x, a new minor version (0.2.0) may change behaviour: move to it deliberately, by changing the constraint to `^0.2@dev` after reading its changelog entry. From 1.0, `^1.0` will follow every compatible release, and a future 2.x will get its own [documentation version](/). These docs (`/1.x/`) describe the 0.x betas leading to 1.0. Your `composer.lock` records the exact framework commit, so every server installs the version you tested. Commit it after each update. ## Where the package comes from The framework is on [Packagist](https://packagist.org/packages/tinytank/framework), Composer's default source. The skeleton's `composer.json` also lists a local folder: ```json "repositories": [ { "type": "path", "url": "packages/*", "options": { "symlink": true } } ] ``` It's for TinyTank maintainers, who work on the framework in a local clone in `packages/` (see [Contributing](../contributing)). In your site, `packages/` stays empty and Composer uses Packagist. You can delete the entry and the `packages/` folder if you never work on the framework itself. ## Skeleton changes Improvements to the skeleton (new example templates, config defaults) don't reach existing sites automatically, because your site's files are yours. When a framework release needs a change in your files, its notes and these docs say so. --- --- url: https://docs.tinytank.dev/1.x/accessibility.md --- # Accessibility A site should work for everyone who visits it: with a keyboard, a screen reader, voice control, zoomed in, with less motion, in bright sunlight. TinyTank builds the basics in, and checks every page of your site for the rest on every push. This section covers: * **What's built in** (below): what the framework and the skeleton already do, and what's yours. * [Checking](./checking): the automated checks (axe, in both themes, blocking CI), how to run them before you push, and what they can't see. * [Colour and contrast](./contrast): the most common problem, and how to fix it without redesigning. ## What's built in **In the skeleton's layout and CSS** (your files: adapt them freely, `tests/e2e/accessibility.spec.js` checks they keep working): * **A skip link**, the first thing keyboard users reach: "Skip to content" slides in on focus and moves the focus past the navigation to `<main id="main">`. * **Visible keyboard focus**: `:focus-visible` gets an outline in the theme's `primary` colour, on every element. Mouse clicks don't trigger it on links and buttons, so they stay clean. * **Reduced motion**: visitors whose system asks for less motion get no movement: animations stop, transitions keep only colours and opacity (a hover still fades, nothing slides), and scrolling isn't smooth (`@media (prefers-reduced-motion: reduce)` in `resources/css/app.css`). * **The page's language**, `<html lang="…">`, in every language, so screen readers pronounce it right. * **The contact form**: each field has a label; a mistake is linked to its field (`aria-invalid`, `aria-describedby`), the form's own problems are an alert (`role="alert"`) and "sent" a status (`role="status"`); while it's being sent, the button is disabled and busy (`aria-busy`). On a static site too. **In the framework**, for every site: * **Images** keep the alt text you write in Markdown (`![A red bicycle](bike.jpg)`) in their responsive `<picture>`. Write one for every image that says something; `![](divider.png)` is for decoration. * **Task lists** (`- [x] Done`): each checkbox is named after its item, so a screen reader says "Done, checkbox, checked". * **Videos** (`::youtube`, `::vimeo`): the poster is a button named "Play video: the title", and a plain link to the video without JavaScript. * **Datastar's ARIA states**: `data-attr` writes a boolean as a bare attribute or removes it, so ARIA states are written as strings: `data-attr:aria-expanded="String($open)"`. ## Movement you add A card that lifts or a row that slides on hover goes behind Tailwind's `motion-safe:` (`motion-safe:hover:-translate-y-1`): with less motion it simply doesn't happen, instead of jumping. An effect a visitor switches on knowingly (an animated background they enabled) can keep moving with the class `motion-allowed`. ## Interactive components Dialogs, toasts and sliders aren't part of TinyTank: native HTML (`<dialog>`, `<input type="range">`) already handles the keyboard and screen readers, and Datastar wires it, styled your way. Prefer a native element to a `<div>` with ARIA roles: it does the right thing without extra work. --- --- url: https://docs.tinytank.dev/1.x/accessibility/checking.md --- # Checking Every page of your site is checked with [axe-core](https://github.com/dequelabs/axe-core), the engine behind most accessibility tools, in the light and the dark theme, against **WCAG 2.2 AA** and axe's best practices. It runs with the browser tests, so a problem **fails CI**: it can't reach the live site unnoticed (and a site that publishes from CI isn't published). ## The four moments From the fastest feedback to the safety net: 1. **While you design.** In Chrome's DevTools, the colour picker shows the contrast ratio of the text you inspect, with a line at 4.5:1; Firefox's accessibility panel does the same. The free [axe DevTools](https://www.deque.com/axe/devtools/) extension checks the page you're on in a second. That's the cheapest moment to catch contrast: before a colour spreads to every template. 2. **Before you commit**, after a template or CSS change: ```sh npm run build # the checks run against a build, like the other browser tests npm run test:a11y # about half a minute: every page, both themes ``` 3. **Before you push, automatically** (optional): the skeleton has a Git hook that runs the same two commands and stops the push if something fails. Turn it on once per clone: ```sh git config core.hooksPath .githooks ``` `git push --no-verify` skips it for one push. With DDEV, push from inside the container (`ddev ssh`), where the browser is, or set `CHROMIUM_PATH`. 4. **In CI**, always: `npm run test:e2e` includes the checks. A failure stops the job, and the publish job after it. Coding agents get the same instruction in `AGENTS.md`: run `npm run test:a11y` after changing templates or CSS. ## What a failure looks like ``` 2 accessibility problem(s): /blog: Elements must meet minimum color contrast ratio thresholds (color-contrast, serious) time[datetime="2026-09-27"] Fix any of the following: Element has insufficient color contrast of 4.12 (foreground color: #79716b, background color: #0c0a09, font size: 10.5pt (14px), font weight: normal). Expected contrast ratio of 4.5:1 https://dequeuniversity.com/rules/axe/4.14/color-contrast ``` Each problem names the page, the rule, the element (a CSS selector) and what to change, with a link to the rule's explanation. Which theme is in the test's name (`the dark theme › every page…`). ## The test `tests/e2e/axe.spec.js` reads the pages from `/sitemap.xml`: every page and translation a search engine would see. A page left out of the sitemap (an unlisted page) isn't checked; neither are the states a page reaches after clicking (an open menu, a form with errors): check those with a test of their own (`new AxeBuilder({ page }).include('#menu').analyze()` after opening it). ### Accepting a problem, visibly Sometimes a problem can't be fixed today (a third-party widget, a design waiting for a decision). The test has a list for that, which should stay empty: ```js // [rule, part of the element's selector, why] const EXCEPTIONS = [ ['color-contrast', '.legacy-banner', 'replaced in the next release (issue #12)'], ]; ``` The check passes, and the exception is in the code, where a review sees it, instead of a check that's switched off. ## What the checks can't see Automated checks find the measurable problems (contrast, names, labels, ARIA misuse, structure), about a third to a half of what can go wrong. Before a launch, and after a big change, try the site yourself: * **Keyboard only**: Tab through a page. Can you reach everything, see where you are, and use it (menus, the theme switch, forms, video)? Does the focus go somewhere sensible after an action? * **Zoom to 200%**, and a narrow window: nothing cut off or overlapping, no sideways scrolling for text. * **A screen reader** for a few minutes: VoiceOver (macOS, iOS), NVDA (Windows, free), TalkBack (Android). Do headings, links and buttons say what they do? Is a form's result announced? * **Reduced motion** on (your system's accessibility settings): nothing moves that the visitor didn't ask for. * **Alt text** reads well out of context, and decorative images have none. --- --- url: https://docs.tinytank.dev/1.x/accessibility/contrast.md --- # Colour and contrast Low contrast is the most common accessibility problem on the web, and the easiest to fix: text has to stand out from what's behind it, for people with low vision, on a phone in the sun, on a cheap screen. ## The numbers (WCAG 2.2 AA) | Text | Minimum contrast | |---|---| | Body text (below 24px, or 18.66px bold) | **4.5:1** | | Large text (24px and up, or 18.66px bold and up) | 3:1 | | Icons and borders that carry meaning (a field's outline, a chart's line) | 3:1 | | Logos, disabled controls, pure decoration | none | Text hidden from screen readers (`aria-hidden`) still counts: it's still read by eyes. ## Both themes A palette tuned for one theme often fails in the other: an accent that glows on black is too light on cream, a grey that's quiet on white disappears on dark grey. The checks run every page in both, and the test's name says which failed. ## Fixing a colour without redesigning Work on the **token**, not on each element: the colour in `resources/css/app.css` (`--color-subtle`, or your own), so every use changes at once. 1. Find the failing pair in the report: `foreground color: #d4146e, background color: #f3ebe1`, and the contrast it has (4.31) against what it needs (4.5). 2. **Darken (on a light background) or lighten (on a dark one) the same hue** until it reaches 4.5:1 on *every* background it's used on: the page, cards, code blocks. A few percent of lightness is usually enough, and the colour still reads as the same colour. DevTools' colour picker shows the ratio as you drag. 3. If the colour is a brand colour that must stay exact, keep it for large text, borders and backgrounds, and use a darker shade for small text. 4. Text on a coloured background (a button, the current page in a pager) can switch to the other ink: dark text on a bright colour is often easier than a darker colour. Two things that look fine and fail: * **Opacity**: `opacity-75` on text lowers its contrast against the background; give it a colour that passes instead. * **Text over images**: it passes or fails depending on the picture. Put it on a solid or darkened band, not straight on the photo. --- --- url: https://docs.tinytank.dev/1.x/static-site-generator.md --- # Static Site Generator The same TinyTank site can be published two ways: as the **PHP site** (on a server with PHP, [Deploying](../deployment/)), or as **plain files** for a static host such as Cloudflare, with no PHP on the server. TinyTank is then a static site generator, with everything you develop with: Twig templates, Markdown content, data collections, translations, SEO, responsive images, Datastar in the browser, and even forms. You keep developing as usual (`npm run dev`, the PHP site at your local address); only the last step changes: ```sh npm run build # the CSS and JavaScript php bin/console build:static # the whole site, as files, in deploy/ php bin/console preview:static # check it locally, as the host will serve it php bin/console publish:static # put it online (Cloudflare Workers) ``` ## Static or PHP? | | Static | PHP | |---|---|---| | Hosting | free on Cloudflare for most sites; nothing to maintain or update | a server with PHP 8.4 | | Speed and resilience | every page is a file, served from Cloudflare's network | fast too (compiled ahead of time, [CDN caching](../deployment/cdn) optional) | | Forms | sent by a small Worker ([Forms](./forms)): checks and spam honeypot, no rate limit | everything ([Forms](../features/forms)) | | Server-side features | none: [what needs the server](./what-needs-the-server) is listed by the build | routes and controllers, Datastar server actions | | Changes go live | rebuild and publish | `bin/console deploy` | Most sites that only show content (a studio, a portfolio, a blog, documentation) can be static. You can switch at any time: the same site builds both ways. ## In this section * [How it works](./how-it-works): how pages are found and written, and broken links. * [Configuration](./configuration): the `static` options in `config/app.php`. * [What needs the server](./what-needs-the-server): what can't work without PHP, and `site.static`. * [Search](./search): the blog search, filtered in the browser. * [Forms](./forms): contact forms answered by a Cloudflare Worker. * [Hosts](./hosts): Cloudflare, any static host, or your own adapter. * [Preview](./preview): the build served locally, exactly as published. * [Publishing](./publishing): the API token and `publish:static`. * [Troubleshooting](./troubleshooting): what can go wrong, and how to find out why. --- --- url: https://docs.tinytank.dev/1.x/static-site-generator/how-it-works.md --- # How it works `build:static` renders every page through your site, in production mode, exactly as the PHP site would answer it, and writes it as a file. ```sh npm run build php bin/console build:static --base-url=https://example.com ``` The whole site is then in `deploy/`, ready for [Cloudflare Workers](https://developers.cloudflare.com/workers/static-assets/) (free for most sites); [Publishing](./publishing) puts it online. ## Where pages go Each page is written where the host serves it at the same URL as the PHP site: for Cloudflare, `/blog/my-post` becomes `deploy/blog/my-post.html`, which Cloudflare serves as `/blog/my-post` (and redirects `/blog/my-post/` and `/blog/my-post.html` there). `/sitemap.xml` stays `deploy/sitemap.xml`. Other hosts are described in [Hosts](./hosts). ## How pages are found The build follows links, starting from the home page, the sitemap, the feed and `robots.txt`: every post, page, collection item, page of a list and translation that something links to. Pages nothing links to (like an unlisted page) go in `static.paths` ([Configuration](./configuration)). ## Files and media It also copies `public/` (your asset build, the favicon, other files; not PHP) and publishes the images and files of posts, pages and collections, with their responsive versions, then writes `404.html` for unknown addresses. The build has its own cache (`var/static-cache/`), so your development cache isn't touched. It only ever empties a folder it wrote itself (marked by a `.tinytank-static` file). ## Broken links A link to a file that doesn't exist (`/media/…`, `/build/…`) or a page that doesn't answer 200 fails the build, with the page it was linked from: ``` /media/nowhere/gone.pdf is missing (linked from /legal) ``` The build also stops when a page uses something that needs the server: see [What needs the server](./what-needs-the-server). --- --- url: https://docs.tinytank.dev/1.x/static-site-generator/configuration.md --- # Configuration Everything is optional, in `config/app.php`: ```php 'static' => [ 'out' => 'deploy', // the output folder (or --out) 'base_url' => 'https://example.com', // the site's address once published (or --base-url; // default APP_URL): used in the sitemap, the feed and share tags 'paths' => ['/style-guide'], // pages nothing links to 'host' => 'cloudflare', // or 'none', or your own class (Hosts); or --host 'name' => 'my-site', // the Worker's name on Cloudflare (default: the site's name) 'domains' => ['example.com'], // your domains on Cloudflare (default: the workers.dev address) ], ``` | Option | | |---|---| | `out` | the folder the site is written to, relative to the site (default `deploy`) | | `base_url` | the published address; links in the sitemap, the feed and share tags use it | | `paths` | pages the build can't find by following links ([How it works](./how-it-works#how-pages-are-found)) | | `host` | where the site is published ([Hosts](./hosts)) | | `name` | the Worker's name on Cloudflare (written in lowercase with dashes: `Lab 909` becomes `lab-909`) | | `domains` | domains managed by Cloudflare that point at the site ([Publishing](./publishing)) | Forms have their own static settings, in `config/forms.php`: see [Forms](./forms). Secrets never go here: the Cloudflare API token and the mail server's password are in `.env` ([Publishing](./publishing)). --- --- url: https://docs.tinytank.dev/1.x/static-site-generator/what-needs-the-server.md --- # What needs the server A static site has no PHP behind it, so some features can't work there: * Datastar actions that call the server: a template action (`datastar.get('_partials/search')`), a POST to a route (the skeleton's clock). A plain GET of a page of the site (`datastar.action('get', path('blog_search'))`) is fine: the build writes that page too, and the file answers it ([Search](./search) works this way). * Forms that post to the site, unless the host answers them ([Forms](./forms)). * Anything a controller computes on each request: it runs once, at build time, and the result is the file. The build finds them on every page and stops with a list: ``` /blog: a Datastar GET action to the server (template _partials/blog-results) /contact: a form posting to the site (/contact) ``` Browser-only Datastar keeps working (toggles, tabs, the theme, anything with `data-signals` and no `@get`/`@post`), and so do JavaScript modules. ## `site.static` Templates can tell they're being rendered for a static build: ```twig {% if not site.static %} {# the live search: only on the PHP site #} {% endif %} ``` `--allow-dynamic` builds anyway, with the list as a warning. --- --- url: https://docs.tinytank.dev/1.x/static-site-generator/search.md --- # Search The skeleton's blog search works on a static site too. On the PHP site the server filters the posts (`_partials/blog-results.twig`); in a static build the browser does: * `/blog/search` (route `blog_search`, `templates/blog/search.twig`) lists every post, each with its words and tags in `data-words` and `data-tags`, and shows while it matches: `data-show="($tag === '' || el.dataset.tags.split(' ').includes($tag)) && el.dataset.words.includes($q.trim().toLowerCase())"`. It's marked `noindex`, and its route stays out of the sitemap (`sitemap: false`); the build finds it through the search box. * In a static build, the search box and tag buttons load it on first use with a plain Datastar GET, in place of an empty `#blog-search`, and hide the page's own list while a search or tag is active: ```twig {% set filter = site.static ? '$_all || ($_all = true, ' ~ datastar.action('get', path('blog_search')) ~ ')' : '$page = 1; ' ~ datastar.get('_partials/blog-results') %} ``` ## Searching anything else The same pattern searches anything else (a collection, a catalogue): a page listing every item with its words, loaded on first use, filtered by Datastar in the browser. It suits a few hundred items; the whole list is one request. --- --- url: https://docs.tinytank.dev/1.x/static-site-generator/forms.md --- # Forms A form from `config/forms.php` keeps working on a static site when its host can send it. On Cloudflare, the build adds a small Worker that answers the form, checks it like the PHP site does and emails it to you. Every page stays a plain file; the Worker only runs for the form. It sends in one of two ways (`static.send`): * **`smtp`: your own mail server** (your domain's mailbox, your email provider's SMTP), on Cloudflare's free plan. The Worker connects to it like a mail program: port 465 (TLS), or 587 or another port with STARTTLS, which the server must offer: the password and the message never travel unencrypted, and a server without TLS gets nothing. Cloudflare blocks port 25. * **`cloudflare`** (the default): Cloudflare's [Email Service](https://developers.cloudflare.com/email-service/), through a binding locked to the form's recipients. It needs a paid Workers plan and the sending domain set up there. ## Setting up a form 1. Give the form a sender, in `config/forms.php`: ```php 'contact' => [ 'fields' => [...], 'to' => getenv('CONTACT_TO'), // the PHP site's recipient (in development, DDEV's Mailpit) 'static' => [ 'from' => 'contact@example.com', // an address your mail server may send from 'to' => 'you@example.com', // the static site's recipient; without it, the form's `to` 'send' => 'smtp', ], ], ``` Rather keep the addresses out of the repository? Read them from `.env`, and leave the form without `static` when they aren't set (tests, CI): `'static' => getenv('STATIC_MAIL_FROM') ? [...] : null`. 2. Let the form's template post to the host in a static build. `form_action()` is the page's own URL on the PHP site and `/forms/<name>` in a static build; send it with Datastar, so the answer comes in place and nothing typed is lost (without JavaScript it's a plain post to the same address). The skeleton's `templates/_forms/contact.twig` does all of this: ```twig <form id="contact-form" method="post" action="{{ form_action('contact', url) }}" data-on:submit__prevent="{{ datastar.action('post', form_action('contact', url), {contentType: 'form'}) }}"> {{ form_spam('contact') }} {# first: see below #} {% if site.static %} <p role="alert" data-show="$_forms.contact.errors._form" data-text="$_forms.contact.errors._form" style="display: none"></p> {% endif %} <input name="email" type="email" required {% if site.static %}aria-describedby="contact-email-error" data-attr:aria-invalid="String(!!$_forms.contact.errors.email)"{% endif %}> {% if site.static %} <p id="contact-email-error" data-show="$_forms.contact.errors.email" data-text="$_forms.contact.errors.email" style="display: none"></p> {% endif %} … ``` * The form needs an **`id`**: the host replaces the form, by that id, with its sent state, which the build takes from the form page's sent version (`/contact/sent`). * Mistakes come back as signals: `$_forms.<form>.errors.<field>` per field and `$_forms.<form>.errors._form` for the whole form (too many links, a message that couldn't be sent); `''` when fine. In a static build, `form_spam()` creates them, so it goes **before** the elements that read them. * On the PHP site, the same Datastar post goes to the page, which renders the form again with its errors (`form.errors`), as before. 3. With `smtp`, put the mail server's settings in `.env`: ```ini SMTP_HOST=mail.example.com SMTP_PORT=465 SMTP_USER=contact@example.com SMTP_PASSWORD='…' ``` Write passwords in **single quotes**: unquoted or in double quotes, `.env` reads `$NAME` as a variable, and a password with a `$` reaches the server changed ("535 Authentication failed"). `publish:static` warns about it. `publish:static` hands them to Cloudflare as the Worker's encrypted secrets, after each deploy (`wrangler secret bulk`, on its input: never in a file); they're never in the build. The server must accept connections from Cloudflare's addresses, as from any mail program. With `cloudflare`, set up the sending domain in the dashboard's **Email Service** instead; the build adds the binding. 4. Publish (`php bin/console publish:static`, [Publishing](./publishing)) and send yourself a message. If you get "Your message wasn't sent", the Worker's log says why: see [Troubleshooting](./troubleshooting#a-form-says-your-message-wasn-t-sent). ## What happens on the static site * The visitor's message is checked like on the PHP site: required fields, lengths, email format, choices, the honeypot and the links limit, with the same messages in the page's language. * A valid message is emailed to you, from the form's `static.from`, with the visitor in Reply-To; the form turns into its **sent** state in place (without JavaScript, the visitor lands on `/contact/sent`, the page as it shows after sending). * Mistakes show next to their fields, and a message that couldn't be sent above the form; what was typed stays (browsers catch most mistakes before sending, from the same rules). Without JavaScript, a short page lists them, with a link back to the form. * A bot that fills the hidden field is told it worked; nothing is sent. * With the `timing` check, the build signs a token into the form's pages (`form_spam()` prints it) and the Worker only takes posts that carry it: a script posting to `/forms/contact` without loading the page is told it worked, and nothing is sent. The pages are files, so the token is the same for every visitor until the next build; a build makes the tokens of older builds expire a day later, and a visitor with a page that old is asked to reload it. The key it's checked with is derived from `APP_SECRET` and written in `worker.js`, which is never served; `APP_SECRET` itself stays on your machine. Build with the same `APP_SECRET` every time, or pages opened before a build stop posting at once. * A body larger than 100 KB is refused, however it's sent. ## When a message can't be sent The visitor sees it (above the form, with what they wrote kept) and can try again later; the Worker's log says why ([Troubleshooting](./troubleshooting#a-form-says-your-message-wasn-t-sent)). To hear about it yourself, add the [Pushover](https://pushover.net) keys to `.env`, the same ones as the PHP site's [push alerts](../features/logging#push-alerts): ```sh PUSHOVER_TOKEN=… # the application's API token PUSHOVER_USER=… # your user key ``` `publish:static` uploads them as the Worker's secrets, with any form. A message that can't be sent then pushes an alert to your phone, titled with the site and the form, with the error (`A message wasn't sent: The mail server answered 535: …`) and a link to the form's page. Never what the visitor wrote. The alert goes out after the visitor has the answer, and at most once an hour from a running Worker, so a broken mail server doesn't flood your phone. The most common cause is the mail server itself (a changed password, a server refusing Cloudflare's connections), which is why the alert doesn't go by email. ## What it doesn't do These need the PHP site: timing each submission (the static token says the post comes from the site's pages, not how long the visitor took) and the rate limit, your own rules (`$app->forms->rule()`), and a custom email template (`_emails/<form>.txt.twig`). The static site's email lists every field, like the default template. Without a rate limit, a script that loads the page first can still post as often as it likes. If that happens, add a [rate limiting rule](https://developers.cloudflare.com/waf/rate-limiting-rules/) for `/forms/*` in Cloudflare's dashboard (one rule is free). ::: tip Privacy The message goes through Cloudflare (your host), and your mail server with `smtp`, to you, and isn't stored. Say so on your privacy page. ::: --- --- url: https://docs.tinytank.dev/1.x/static-site-generator/hosts.md --- # Hosts The PHP site sends more than pages: with each one, headers (the Content Security Policy, which tells browsers what may run on the page, and other protections), and redirects (`/blog/page/1` to `/blog`, and the site's own [redirect map](../basics/routing#redirects)). A static host has no PHP to send them, so the build writes them in the host's own files. | `host` | Files | | |---|---|---| | `cloudflare` (default) | `<path>.html`, `_headers`, `_redirects`, `wrangler.jsonc`, and for [forms](./forms) `worker.js` | [Cloudflare Workers](https://developers.cloudflare.com/workers/static-assets/) with static assets | | `none` | `<path>.html`, redirects as small HTML pages | any other host (GitHub Pages, a plain web server); the headers are lost | ## Cloudflare `_headers` holds one rule for the whole site. Its Content Security Policy is the strictest one that still lets every page work: what pages add to `img-src`, `media-src`, `frame-src`, `font-src` or `style-src` (a video player's frame) is allowed site-wide, which is safe, since those can't run code in the page; `script-src` and `connect-src` stay as the PHP site has them. A page that adds a script source (`csp_allow()` in its template) gets a rule of its own. The build stops if the site needs more rules than Cloudflare allows (100), or more redirects (2,000). Vite's hashed files (`/build/…`) are cached for a year. `wrangler.jsonc` tells `npx wrangler deploy` what to publish; it, `worker.js` and `.assetsignore` (the list of files never served) stay private. ## Your own host A class implementing `TinyTank\Static\HostAdapter`, named in `config/app.php` (`'host' => App\Static\MyHost::class`), with a constructor without arguments: ```php use TinyTank\Static\Build; use TinyTank\Static\HostAdapter; final class MyHost implements HostAdapter { /** Where a page goes, so the host serves it at the same URL: '/blog' → 'blog.html'. */ public function file(string $path): string { … } /** * The host's own files, path => contents, from the build: $build->pages (each with the * `headers` the PHP site sends it) and $build->redirects (`to`, `status`). */ public function files(Build $build): array { … } } ``` --- --- url: https://docs.tinytank.dev/1.x/static-site-generator/preview.md --- # Preview See the build exactly as it'll be published, before uploading it: ```sh php bin/console build:static php bin/console preview:static # http://localhost:4173 ``` For the `cloudflare` host it runs Cloudflare's own local server on `deploy/` (`wrangler dev`): the same URLs, redirects, headers and Content Security Policy as on Cloudflare, and the forms' Worker, which writes its emails to files in `deploy/.wrangler/tmp/email/` instead of sending them. It uses the site's `wrangler` if it's installed (`npm i -D wrangler`), otherwise `npx` downloads it once. `--php` uses PHP's built-in server instead, without Node: pages, files and redirects, but not the host's headers or the forms. Options: `--port` (4173), `--ip` (`0.0.0.0`, so DDEV can reach it), `--out`, `--dry-run` (only print the command). With DDEV, the skeleton exposes the port: open `https://<project>.ddev.site:4173` (after a `ddev restart` if you added the port to an existing site's `.ddev/config.yaml`). --- --- url: https://docs.tinytank.dev/1.x/static-site-generator/publishing.md --- # Publishing On Cloudflare Workers, with Cloudflare's command line tool, `wrangler` (it needs Node.js; `npx` fetches it, or install it in the site with `npm i -D wrangler`): 1. Set the site's public address and domain in `config/app.php`. The domain must be managed by Cloudflare (its DNS on Cloudflare); Cloudflare points it at the site and makes its certificate: ```php 'static' => [ 'base_url' => 'https://example.com', 'domains' => ['example.com'], ], ``` 2. Create an API token (once), so wrangler can publish without a browser login (which a container can't receive). In the Cloudflare dashboard, **Manage Account** → **Account API Tokens** → **Create Token** (or **My Profile** → **API Tokens** for one tied to you), and give it **two policies**. Workers permissions belong to the account, so a policy limited to a domain doesn't grant them, even with the right boxes ticked: | Policy | Resource | Permissions | |---|---|---| | 1 | your account | **Workers Scripts: Edit**, **Account Settings: Read**, **Workers Tail: Read** (for `wrangler tail`, the forms' logs) | | 2 | **Specified Domains** → the site's domain | **Workers Routes: Edit** (connects `domains` to the Worker) | The **Edit Cloudflare Workers** template ticks these and more (KV, R2, Pages…, not needed); check the template didn't put them all under the domain's policy. Copy the token (shown once) into `.env`, with your account ID (on the dashboard's home page, or any domain's overview): ```ini CLOUDFLARE_API_TOKEN=… CLOUDFLARE_ACCOUNT_ID=… ``` `.env` is never committed, and nothing from it is written in the build. Editing a token's policies later keeps its value. If wrangler answers "No access to the specified resource", see [Troubleshooting](./troubleshooting#no-access-to-the-specified-resource). 3. Build and publish: ```sh php bin/console publish:static # with DDEV: ddev exec php bin/console publish:static ``` It runs `build:static`, then `wrangler deploy` in the output folder (`--no-build` publishes the existing build; `--dry-run` only shows the command). The first deploy creates the Worker (named after `static.name`, or the site) and connects the domains; later ones replace the files. Without `domains`, the site is at `https://<name>.<your-account>.workers.dev`. Rather log in through a browser? From a terminal on your computer: `npx wrangler login` once, then `npx wrangler deploy` in `deploy/` after each `build:static` (forms sent over SMTP need their secrets once: `npx wrangler secret put SMTP_PASSWORD`, and the same for the other keys). 4. Check the live site: its pages, and a message through each form. Each deploy publishes everything again, so it's always the build's exact copy; Cloudflare keeps earlier versions, to roll back in its dashboard. ## What `publish:static` does 1. Checks `CLOUDFLARE_API_TOKEN` and `CLOUDFLARE_ACCOUNT_ID` are set (in `.env` or the environment). 2. Runs `build:static` (unless `--no-build`), and checks the build is for Cloudflare. 3. Runs `wrangler deploy` in the output folder, with the site's own `wrangler` (`npm i -D wrangler`) or `npx wrangler@4`. 4. For [forms sent over SMTP](./forms): sets `SMTP_HOST`, `SMTP_PORT`, `SMTP_USER` and `SMTP_PASSWORD` from `.env` as the Worker's encrypted secrets (`wrangler secret bulk`, on its input: never written to a file). It warns about a `$` outside single quotes in those values, and stops if a form needs `SMTP_HOST` and it's missing. With any form, `PUSHOVER_TOKEN` and `PUSHOVER_USER` too, when both are set ([alerts](./forms#when-a-message-can-t-be-sent)). | Option | | |---|---| | `--no-build` | publish the existing build (after `build:static` and `preview:static`, say) | | `--dry-run` | only show the commands; nothing is built, uploaded or written | ## From GitHub Actions Publish on every push to `main` whose tests pass: a second job in the site's CI workflow (`.github/workflows/ci.yml`), after the `test` job. ```yaml publish: name: Publish on Cloudflare needs: test if: github.event_name == 'push' && github.ref == 'refs/heads/main' runs-on: ubuntu-latest concurrency: # one publish at a time; a newer push waits group: publish cancel-in-progress: false env: APP_URL: https://example.com APP_SECRET: ${{ secrets.APP_SECRET }} CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }} CLOUDFLARE_ACCOUNT_ID: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }} # Only for forms sent over SMTP, and the addresses config/forms.php reads from the environment: SMTP_HOST: ${{ secrets.SMTP_HOST }} SMTP_PORT: ${{ secrets.SMTP_PORT }} SMTP_USER: ${{ secrets.SMTP_USER }} SMTP_PASSWORD: ${{ secrets.SMTP_PASSWORD }} # Optional: a push to your phone when a message can't be sent (Pushover): PUSHOVER_TOKEN: ${{ secrets.PUSHOVER_TOKEN }} PUSHOVER_USER: ${{ secrets.PUSHOVER_USER }} steps: - uses: actions/checkout@v4 - uses: shivammathur/setup-php@v2 with: php-version: '8.4' extensions: intl, mbstring, gd # gd: images are published without their metadata coverage: none tools: composer:v2 - uses: actions/setup-node@v4 with: node-version: '24' cache: npm - name: Install dependencies run: | composer install --no-dev --no-interaction --no-progress --prefer-dist npm ci - name: Build assets run: npm run build - name: Check run: php bin/console check - name: Build and publish run: php bin/console publish:static ``` Then, in the repository's **Settings** → **Secrets and variables** → **Actions**, add each `secrets.…` above as a repository secret, with the values from your `.env`. GitHub passes them as environment variables, which `publish:static` reads like `.env`; nothing is written to a file, and GitHub hides the values in the logs. Paste a password as it is, without the quotes `.env` needs. * The site's `.env` stays on your computer: the workflow needs only these variables. * `composer install` uses `composer.lock`, so the site is published with the framework version it was tested with. * `check` stops the job before anything is published if the build would break the site; it also lists the image formats the runner can write (GD writes AVIF and WebP when it was built with them). * A failed publish shows wrangler's message in the job's log; see [Troubleshooting](./troubleshooting). ## Running wrangler yourself Other wrangler commands (the forms' logs, versions, rollbacks) read the same token with `--env-file`, from the output folder: ```sh cd deploy npx wrangler tail --env-file ../.env # the Worker's live logs npx wrangler deployments list --env-file ../.env ``` --- --- url: https://docs.tinytank.dev/1.x/static-site-generator/troubleshooting.md --- # Troubleshooting What can go wrong when building, previewing and publishing a static site, and how to find out why. ## Building ### "Vite manifest not found" The pages need the CSS and JavaScript build: run `npm run build` before `build:static` (the dev server, `npm run dev`, isn't used by the static build). ### The build stops with a list of pages ``` /blog: a Datastar GET action to the server (template _partials/blog-results) /contact: a form posting to the site (/contact) ``` These pages use something that needs PHP. Wrap it in `{% if not site.static %}`, give the form a `static` sender, or load a page with a plain GET: see [What needs the server](./what-needs-the-server) and [Forms](./forms). `--allow-dynamic` builds anyway, to look at the rest. ### "is missing (linked from …)" A link points to a file or page that doesn't exist: fix the link in the page named after "linked from" ([Broken links](./how-it-works#broken-links)). ### A page is missing from the build The build only finds pages something links to. Link to it, or add it to `static.paths` ([Configuration](./configuration)). Unlisted pages (`unlisted: true`) are never linked from menus or the sitemap, so they always need `static.paths`. ### The host's limits On Cloudflare the build stops above 100 header rules or 2,000 redirects. Header rules come from pages that add a script source (`csp_allow()`): load that script on fewer pages, or allow it site-wide in `csp.sources`. ## Previewing ### The port is taken `preview:static` listens on 4173; another program may already use it: `--port 4174`. With DDEV, the port must also be in `.ddev/config.yaml` (`web_extra_exposed_ports`), then `ddev restart`. ### `wrangler dev` doesn't start It needs Node.js (DDEV has it). `--php` serves the build with PHP's built-in server instead: pages, files and redirects, but not the host's headers or the forms. ## Publishing ### "CLOUDFLARE_API_TOKEN and CLOUDFLARE_ACCOUNT_ID must be set" `publish:static` reads them from `.env` (or the environment). Create the token as in [Publishing](./publishing), and copy the account ID from the Cloudflare dashboard's home page. ### "No access to the specified resource" Or "Authentication error". Cloudflare refused the token: it's valid, but lacks a permission for what wrangler asked. Most often the Workers permissions are in a policy limited to a domain (**Specified Domains**), where they don't count: Workers belong to the account. Edit the token (**Manage Account** → **Account API Tokens**, or **My Profile** → **API Tokens**) so it has two policies: | Resource | Permissions | |---|---| | your account | **Workers Scripts: Edit**, **Account Settings: Read**, **Workers Tail: Read** | | **Specified Domains** → the site's domain | **Workers Routes: Edit** | Editing the policies keeps the token's value: run `publish:static` again. If it still fails, check `CLOUDFLARE_ACCOUNT_ID` is the account the token belongs to. ### The token is refused for everything If even the first request fails, the token in `.env` isn't one Cloudflare knows: copied incompletely, rolled, deleted or expired. Create a new one and replace `CLOUDFLARE_API_TOKEN`. ### `wrangler login` doesn't work in a container The login opens a browser that sends its answer to `localhost`, which a container (DDEV, Docker, WSL) doesn't receive. Use an API token and `publish:static` instead. ### The domain isn't connected The domain must be managed by Cloudflare (its DNS on Cloudflare) and listed in `static.domains`; the token needs **Workers Routes: Edit** on it. Cloudflare won't connect a domain whose DNS already has a record for that name pointing elsewhere (the previous host): remove that record in the dashboard (**DNS** → **Records**), then publish again. Without `domains`, the site is at `https://<name>.<your-account>.workers.dev`. ### A change doesn't show on the live site Publish again: `publish:static` builds first (unless `--no-build`). Each deploy replaces every file, so the live site is the exact copy of the last build. ## Forms ### A form says "Your message wasn't sent" The Worker couldn't send the message, and its log says why. Follow the log while you send the form again, from the output folder: ```sh cd deploy npx wrangler tail --env-file ../.env ``` The token needs **Workers Tail: Read**. Then send the form; the log shows a line like `Form "contact" not sent: Error: The mail server answered 535: 535 Authentication Failed`: | The log says | What to check | |---|---| | `answered 535` | the mail server refused the login: `SMTP_USER` (often the full address) and `SMTP_PASSWORD`. A password with a `$` must be in **single quotes** in `.env` (`SMTP_PASSWORD='…'`): unquoted or in double quotes, `$NAME` is read as a variable, and the server gets something else. `publish:static` warns about it. | | `answered 550`, `553` or `554` | the server refused the sender or the recipient: `static.from` must be an address that login may send from, and some servers refuse other domains' recipients | | `SMTP_HOST is not set` | the Worker has no secrets: publish with `publish:static` (it sets them), not `wrangler deploy` alone | | a timeout, a refused connection, or `The mail server closed the connection` | the server doesn't accept connections from Cloudflare, or the port is wrong: use 465 (TLS) or 587 (STARTTLS); Cloudflare blocks port 25 | | a TLS or certificate error | the port and its encryption don't match (465 is TLS from the start, 587 starts plain and switches) | After changing `.env`, `php bin/console publish:static --no-build` sends the new secrets. ### "Sent", but nothing arrives Look in the spam folder first. A message from an address of your own domain, sent through your own mail server, is the most likely to be delivered; one whose `static.from` belongs to another domain is often refused or filed as spam (the domain's SPF and DMARC records don't allow your server). Check the server's own log too: the Worker only knows the server accepted the message. A bot that fills the hidden honeypot field is also told "sent", and nothing is sent. ### Emails in development `preview:static` doesn't send anything: the forms' Worker writes each email to a file in `deploy/.wrangler/tmp/email/`. The PHP site in development sends to DDEV's Mailpit. --- --- url: https://docs.tinytank.dev/1.x/deployment.md --- # Deploying This page puts the **PHP site** on a server. To publish the site as plain files instead, with no PHP on the host (Cloudflare Workers, free for most sites), see the [Static Site Generator](../static-site-generator/). ## The deploy command ```sh npm ci && npm run build # or pass --assets to deploy composer install --no-dev --optimize-autoloader php bin/console deploy # in DDEV: ddev console deploy ``` `deploy` runs [its steps](../extending/deploy-steps) in order: check the server and the site, optimize the autoloader, build the new cache (routes, posts, translations, templates, the Vite manifest) and the published files, switch the site to them, refresh the web server's Opcache, and purge the CDN when [CDN caching](./cdn) is on. **Run it after every change**: code, templates, content or configuration. In production, changes aren't picked up until then. ## Build first, switch last While `deploy` builds, the site keeps answering from the current build: the new cache and the published files (`public/media/blog/`, `pages/`, `collections/`) are made aside, in `var/deploy/next/`. Only when every step has succeeded does the `switch` step move them in, in a moment. If anything fails (a post that doesn't compile, a missing template, no Vite build), the deploy stops and **the live site is exactly as it was**. The build it replaced is kept in `var/deploy/prev/`. To go back to it: ```sh php bin/console deploy --rollback ``` It puts the previous cache and files back, then refreshes Opcache and purges the CDN like a deploy. A second `--rollback` undoes the first. It restores what `deploy` builds, not your code: after a `git pull` that broke something, check out the previous commit too. What the site keeps between requests isn't in the cache, so deploys never reset it: the forms' rate limits are in `var/state/`, encoded images in `var/images/`. ## Checking first ```sh php bin/console check ``` A read-only preflight, also run first by `deploy` (its `check` step): it compiles everything into a temporary folder and changes nothing. | Check | | |---|---| | `php` | PHP 8.4 or later, with the extensions TinyTank needs; whether Opcache is on | | `images` | GD or Imagick (an error if the content has images: they can't be published without removing their metadata), AVIF and WebP | | `environment` | `APP_SECRET` (random, 32 characters or more), `APP_URL` (an address, `https://` in production) | | `writable` | `var/` and `public/media/`, by the user running it | | `content` | posts, pages, collections, components, translations and routes compile | | `templates` | every Twig template compiles; each page's template, and its `form:`, exist | | `pages` | no content page is hidden behind a route | | `vite` | the Vite build exists (when there's a `vite.config.js`) and has every entry point templates name in `vite(…)` or `page_scripts` | Errors exit with code 1 (and stop a deploy); warnings don't. `--json` prints the results for CI: ```sh php bin/console check --json | jq '.checks[] | select(.status != "ok")' ``` Run it on a new server before the first deploy: it finds a missing extension or an unwritable folder before anything is built. ## Options | Option | | |---|---| | `--list-steps` | show the steps in order and exit | | `--rollback` | put the previous build back ([above](#build-first-switch-last)) | | `--skip=a,b` | leave steps out | | `--assets` | run `npm run build` first | | `--opcache=cachetool\|reload\|none` | how to refresh Opcache (default: `APP_OPCACHE`, else `cachetool`) | | `--fcgi=…` | PHP-FPM socket or `host:port`, for cachetool (default: `APP_FPM_SOCKET`, else `/run/php-fpm.sock`) | | `--cachetool=…` | the cachetool binary (default: `APP_CACHETOOL`, else `cachetool`) | | `--reload-cmd=…` | the command for `--opcache=reload` (default: `APP_OPCACHE_RELOAD_CMD`) | | `--composer=…` | the Composer binary | | `--no-dev` | exclude `require-dev` packages from the autoloader | | `--skip-composer` | same as `--skip=composer` | | `--skip-opcache` | same as `--opcache=none` | Set the Opcache variables once per server in its `.env`, and a plain `php bin/console deploy` does the right thing everywhere. ## After deploying, locally `deploy` makes the Composer autoloader **authoritative**: new classes in `src/` aren't found until the next deploy. When you go back to development: ```sh php bin/console cache:clear ``` It empties the caches (and `var/deploy/`: there's nothing to roll back to in development), rebuilds the normal autoloader with `composer dump-autoload` (only when a deploy left it authoritative; `--composer=<path>` if Composer isn't on your `PATH`), and removes the post and page files published to `public/media/`, which would otherwise shadow the originals in `content/`. ## Production checklist * \[ ] `.env` (or real environment variables) with `APP_URL`, `APP_SECRET`; `APP_DEBUG` unset * \[ ] PHP 8.4 with `intl`, `mbstring`, `xmlwriter`, `opcache`, and GD or Imagick with WebP; `display_errors=Off`, `log_errors=On` * \[ ] web server root at `public/`, everything else routed to `public/index.php` * \[ ] `php bin/console check` passes on the server * \[ ] `var/cache` and `var/deploy` writable by the deploy user and readable by PHP; `var/log` and `var/state` writable by PHP * \[ ] keep `var/images/` and `var/state/` between deploys (encoded images are reused from there; the forms' rate limits live there) * \[ ] the Opcache mode for this server (`APP_OPCACHE`), see [Servers & Opcache](./servers) * \[ ] HTTPS, and `APP_TRUSTED_PROXIES` if behind a proxy or load balancer * \[ ] `MAILER_DSN`, `MAILER_FROM` and `CONTACT_TO` for the contact form (send yourself a test message) * \[ ] `LOG_ALERT_TO` to hear about errors by email ([Logging](../features/logging)), and the web server's access log turned off or without IP addresses ([Access logs](./servers#access-logs)) * \[ ] behind a CDN: `CDN_CACHE=1` and `CDN_PURGE` with its credentials ([CDN caching](./cdn)), and the CDN in your privacy policy * \[ ] the [style guide](../getting-started/checklist#the-style-guide) at `/style-guide`: still wanted on the live site? --- --- url: https://docs.tinytank.dev/1.x/deployment/servers.md --- # Servers & Opcache ## How TinyTank runs TinyTank is made for **PHP-FPM** (or Apache's mod_php): each request boots the kernel, answers and ends, so nothing is left over from one visitor to the next. Booting costs little, because everything it reads is compiled ahead of time and kept in Opcache's memory. Worker servers that keep one app in memory across requests (FrankenPHP's worker mode, RoadRunner, Swoole) aren't supported yet: the kernel keeps state for the request it answers (the current language, the page's extra CSP sources), which would carry over to the next one. FrankenPHP in its classic mode, one request at a time, works like PHP-FPM. ## Why Opcache needs refreshing For speed, production PHP should not check every file for changes on every request (`opcache.validate_timestamps=0`). The flip side: PHP keeps running the old code until its Opcache is refreshed. The deploy command can't do that by itself, because the command line has its own Opcache. So its last step reaches the **web server's** PHP, in one of three ways. ## Choose a mode per server | Server | `.env` on that server | What deploy does | |---|---|---| | nginx + PHP-FPM | `APP_OPCACHE=cachetool``APP_FPM_SOCKET=/run/php/php8.4-fpm.sock` | invalidates and precompiles every file inside FPM: no slow first requests | | Apache + PHP-FPM (`mod_proxy_fcgi`) | same as nginx | same as nginx | | PHP-FPM without cachetool | `APP_OPCACHE=reload``APP_OPCACHE_RELOAD_CMD="sudo systemctl reload php8.4-fpm"` | a graceful FPM reload empties Opcache; files recompile on first use | | Apache + mod_php | `APP_OPCACHE=reload``APP_OPCACHE_RELOAD_CMD="sudo apachectl graceful"` | a graceful Apache restart empties Opcache | | Shared hosting | `APP_OPCACHE=none` | nothing; hosts normally keep `validate_timestamps=1`, so changes are picked up anyway | Socket names differ per distribution: check `listen =` in the FPM pool config, e.g. `/etc/php/8.4/fpm/pool.d/www.conf`. ### cachetool mode [cachetool](https://github.com/gordalina/cachetool) talks to PHP-FPM directly over its FastCGI socket. Install the pinned, checksum-verified phar (DDEV installs the same one through `.ddev/web-build/Dockerfile.cachetool`): ```sh curl -fsSL -o /usr/local/bin/cachetool https://github.com/gordalina/cachetool/releases/download/10.0.0/cachetool.phar echo "cbe90e7acdde7beafe26b592a753c2b923a99d2033e073dc55e42fba2883bd1d /usr/local/bin/cachetool" | sha256sum -c - chmod 755 /usr/local/bin/cachetool ``` The deploy user needs access to the FPM socket, usually owned by `www-data` with mode `0660`: add the deploy user to that group (`sudo usermod -aG www-data deploy`) or deploy as `www-data`. Deploy checks the connection first (`opcache:status`), because cachetool's other commands report success even when they can't reach PHP-FPM. ### reload mode Give the deploy user passwordless sudo for that one command only, in `/etc/sudoers.d/tinytank`: ``` deploy ALL=(root) NOPASSWD: /usr/bin/systemctl reload php8.4-fpm ``` A graceful reload lets running requests finish: there's no downtime. ## PHP settings ```ini ; files only change on deploy, so skip the per-request stat calls opcache.enable=1 opcache.validate_timestamps=0 opcache.memory_consumption=128 opcache.max_accelerated_files=20000 opcache.interned_strings_buffer=16 display_errors=Off log_errors=On ``` ## nginx ```nginx root /var/www/my-site/public; location /build/ { expires 1y; add_header Cache-Control "public, immutable"; } location /media/ { expires 7d; add_header Cache-Control "public"; try_files $uri /index.php?$query_string; } # SVG images can contain scripts: opened on their own, they run none (see "SVG files" below) location ~* ^/media/.+\.svg$ { expires 7d; add_header Cache-Control "public"; add_header Content-Security-Policy "default-src 'none'; style-src 'unsafe-inline'; sandbox" always; add_header X-Content-Type-Options "nosniff" always; try_files $uri /index.php?$query_string; } location / { try_files $uri /index.php?$query_string; } location ~ \.php$ { include fastcgi_params; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; fastcgi_buffering off; # let Datastar's server-sent events stream immediately fastcgi_pass unix:/run/php/php8.4-fpm.sock; } ``` ## Apache With PHP-FPM (`a2enmod proxy_fcgi rewrite headers expires`): ```apache DocumentRoot /var/www/my-site/public <Directory /var/www/my-site/public> AllowOverride None Require all granted FallbackResource /index.php </Directory> <FilesMatch "\.php$"> SetHandler "proxy:unix:/run/php/php8.4-fpm.sock|fcgi://localhost" </FilesMatch> # Let Datastar's server-sent events stream immediately <Proxy "fcgi://localhost"> ProxySet flushpackets=on </Proxy> <Location /build/> Header set Cache-Control "public, max-age=31536000, immutable" </Location> <Location /media/> Header set Cache-Control "public, max-age=604800" </Location> # SVG images can contain scripts: opened on their own, they run none (see "SVG files" below) <LocationMatch "^/media/.+\.svg$"> Header always set Content-Security-Policy "default-src 'none'; style-src 'unsafe-inline'; sandbox" Header always set X-Content-Type-Options "nosniff" </LocationMatch> ``` With mod_php, drop the `FilesMatch` and `Proxy` blocks. ### SVG files An SVG is a document, not just a picture: it can contain scripts. Shown with `<img>` they never run, but someone could link straight to `/media/blog/post/logo.svg`, and then they'd run on your site's address. The rules above give SVG files a policy that allows no scripts and no requests (`sandbox`), the one TinyTank sends in development. In nginx, the regex location takes precedence over `/media/`, so it repeats that location's caching headers. A static build on Cloudflare needs nothing more: its site-wide policy in `_headers` applies to every file, and its `script-src` lets no script written inside an SVG run. ### Caching `/build/` files have a content hash in their name, so they're cached for a year. `/media/` files (post and page images, video posters) keep their name when replaced, so they get a week: a changed image shows up within days without anyone clearing a cache. Rename a file to publish a change at once. ## A CDN for media files Images and videos are usually the heaviest part of a page. To serve them from a CDN, create a "pull" CDN zone whose origin is your site, and set: ```sh MEDIA_URL=https://cdn.example.com ``` Post and page files and video posters then link to `https://cdn.example.com/media/…`, which the CDN fetches from your site's `/media/` the first time and caches. `deploy` still publishes the files to `public/media/`, and the CDN's host is added to the Content Security Policy's `img-src` and `media-src` automatically. Run `deploy` after changing `MEDIA_URL`: post HTML is compiled with it. To cache the pages themselves at a CDN, see [CDN caching](./cdn). ::: tip Apache doesn't allow comments after a directive on the same line, which is why the comment above sits on its own line. ::: ## Health check For an uptime monitor or a load balancer, a route that answers `200` when the site works: ```php // config/routes.php use Symfony\Component\HttpFoundation\Response; $app->get('/health', static function () use ($app): Response { $app->noStore(); // never cached: each check asks the server itself // What the site writes while it runs (the forms' rate limits). $writable = is_dir($app->stateDir) ? is_writable($app->stateDir) : is_writable(dirname($app->stateDir)); return new Response($writable ? 'ok' : 'var/state is not writable', $writable ? 200 : 503, ['Content-Type' => 'text/plain']); }, 'health', sitemap: false); ``` An answer at all means PHP runs, the site starts (its configuration, routes and code) and requests reach it; `503` means it can't record what it should. There's no point in checking the compiled cache: in production a missing cache file is rebuilt on the first request that needs it. Point the monitor at `https://example.com/health`; it answers in a few milliseconds, so checking every minute costs nothing. ## Permissions `var/cache` and `var/deploy` must be writable by the deploy user, and `var/cache` readable by PHP. If PHP ever finds a cache file missing (say, after `cache:clear` without a deploy), it rebuilds it on the fly, so it then needs write access too. `var/log` and `var/state` must be writable by PHP (see [Logging](../features/logging); `var/state` holds the forms' rate limits). `bin/console check`, run as the deploy user, checks the folders it writes to. ## Release directories `deploy` already builds aside and switches at the end, which is enough for most sites. On a server where you control the web root, you can go one step further and give each release its own folder, with a `current` link to the live one, as [Deployer](https://deployer.org) does: the code changes at the same moment as the cache, and going back is moving the link. ``` /var/www/example.com/ ├── current -> releases/42 the web root is current/public ├── releases/41/, releases/42/ one checkout each, built in place └── shared/ the same in every release: .env, var/images, var/state, var/log ``` A `deploy.php` for Deployer 7 (`composer require --dev deployer/deployer`, then `vendor/bin/dep deploy`): ```php <?php namespace Deployer; require 'recipe/common.php'; set('repository', 'git@github.com:you/example.com.git'); set('keep_releases', 5); // Kept across releases: the environment, encoded images, rate limits, logs, video posters. set('shared_files', ['.env']); set('shared_dirs', ['var/images', 'var/state', 'var/log', 'public/media/embeds']); set('writable_dirs', ['var/cache', 'var/deploy', 'var/images', 'var/state', 'var/log']); host('example.com')->set('deploy_path', '/var/www/example.com'); desc('Builds the release (before it goes live)'); task('tinytank:build', function () { cd('{{release_path}}'); run('npm ci && npm run build'); // Opcache is handled after the switch (below): the release's paths are new to PHP. run('php bin/console deploy --opcache=none'); }); desc('Clears PHP-FPM\'s Opcache'); task('php-fpm:reload', function () { run('sudo systemctl reload php8.4-fpm'); }); task('deploy', ['deploy:prepare', 'deploy:vendors', 'tinytank:build', 'deploy:publish']); after('deploy:symlink', 'php-fpm:reload'); after('deploy:failed', 'deploy:unlock'); ``` Point the web server at the link, and have PHP see the real path of each release, so Opcache never mixes two releases' files: ```nginx root /var/www/example.com/current/public; location ~ \.php$ { include fastcgi_params; fastcgi_param SCRIPT_FILENAME $realpath_root$fastcgi_script_name; fastcgi_param DOCUMENT_ROOT $realpath_root; # …as above } ``` Going back is `vendor/bin/dep rollback` (the previous release, code and cache together), then the same FPM reload. (`deploy --rollback` has nothing to go back to there: each release is a fresh checkout, built once.) ## Access logs TinyTank's own [log](../features/logging) records nothing about visitors, but web servers keep an **access log** of every request by default, with the visitor's IP address, the full URL with its query string, the referrer and the browser. That's personal data, kept for as long as the server's log rotation says (often weeks or months). If you don't need it, turn it off, or keep it without the IP address. nginx: ```nginx access_log off; # or: keep the request lines, without who made them log_format private '$time_local "$request_method $uri" $status $body_bytes_sent'; access_log /var/log/nginx/my-site.log private; ``` Apache: ```apache LogFormat "%t \"%m %U\" %>s %b" private CustomLog ${APACHE_LOG_DIR}/my-site.log private ``` `$uri` and `%U` are the path without the query string. Whatever you keep, set how long it's kept (`logrotate`'s `rotate` and `daily`/`weekly`) and mention it in your privacy policy. On shared hosting, the host's control panel usually has these settings. ## Behind a proxy or load balancer Set `APP_TRUSTED_PROXIES` (comma-separated IPs or CIDR ranges, or `REMOTE_ADDR` for the direct peer), so the CSRF origin check sees the public scheme and host from the `X-Forwarded-*` headers. --- --- url: https://docs.tinytank.dev/1.x/deployment/cdn.md --- # CDN caching A CDN (Cloudflare, Bunny, Fastly…) keeps copies of your pages on servers around the world and answers visitors from the closest one. TinyTank can tell it which pages to keep and for how long. You get: * **Speed everywhere:** a visitor far from your server gets the page from a nearby edge server, without the round trip to yours. * **Resilience:** if your server is down or restarting, the CDN keeps serving the last copy of each page, for a day by default. * **A quiet server:** a traffic spike hits the CDN, not PHP. It's **off by default**. A new site goes live without a CDN, and you turn caching on once one is in front of the site. ## Turning it on 1. Put the CDN in front of your site (for Cloudflare, your domain's DNS goes through it; for Bunny, a pull zone with your server as origin, and your domain pointing at it). See [the CDN's own settings](#setting-up-the-cdn) below. 2. In `.env`: ```sh CDN_CACHE=1 CDN_PURGE=cloudflare # or bunny, or command (see Purging) ``` 3. Deploy. ## What the CDN is told Every page now says: ``` Cache-Control: max-age=0, public, s-maxage=3600, stale-if-error=86400, stale-while-revalidate=60 ``` | Directive | Meaning | |---|---| | `public` | the page is the same for everyone, so a shared cache may keep it | | `max-age=0` | **browsers** check back each time: answered by the CDN, it's fast, and visitors always get the current page | | `s-maxage=3600` | the **CDN** keeps the page for an hour (`ttl`) | | `stale-while-revalidate=60` | for a minute after that, the CDN serves the old copy and fetches the new one in the background, so nobody waits for your server | | `stale-if-error=86400` | **if your server is down**, the CDN keeps serving the last copy for a day | The `ttl` is **an hour when the CDN can be purged** (`CDN_PURGE` is set, or a package gave a purger), because `deploy` then clears it. **Without purging it's 5 minutes**, so a change shows up within 5 minutes anyway. ## What's never kept at the CDN TinyTank decides most of this by itself: | What | Why | |---|---| | Pages with a form (the contact page) | Their spam check prints a new token every time; they're `no-store` | | A response that sets a cookie | A cookie is for one visitor: `no-store, private`, whatever its handler said | | A response after `$app->noStore()` | Its handler said it's for one visitor (below) | | The Datastar endpoint, and every request made by Datastar | They answer each request differently | | Errors and redirects | A cached error would be the opposite of resilience | | POST requests, server-sent events | Never cacheable | | A response whose handler set its own `Cache-Control` | The handler knows best: `(new Response(…))->setPrivate()` stays private | And you add: ```php // config/app.php 'cdn' => [ 'exclude' => ['clock'], // route names ], ``` ```md --- title: Today's menu cdn: false # a content page that changes more often than you deploy --- ``` `cdn: false` applies to the page's translations too, unless they set their own. In a controller, `$this->app->cdn->skip()` does the same for the current response. ## Not at the CDN, or nowhere Two different things, for two different reasons: | | `$app->cdn->skip()` (or `exclude`, `cdn: false`) | `$app->noStore()` | |---|---|---| | Means | "not at the CDN": the page changes too often to keep there | "nowhere": the response is for one visitor | | `Cache-Control` | `no-cache, public`, with an ETag: browsers still revalidate it | `no-store, private`, no ETag: nobody keeps it | | Use it for | a clock, today's menu, a live count | an account page, "Hi Ada", a basket | A response that sets a cookie is treated like `noStore()` by itself: TinyTank has no sessions, so a cookie means the response is for that visitor, and keeping it at a CDN would hand it to the next one. A handler that set its own `Cache-Control` (`setPrivate()`, a `max-age`…) keeps it, unless it also sets a cookie. ::: warning Pages that differ per visitor Anything shown to one visitor only must never be `public`. TinyTank has no logins today; code that adds them calls `$app->noStore()` in those responses (a login that sets a cookie gets it anyway). ::: ## Purging **Purging** tells the CDN to drop its copies, so the next visitor gets the new page. `deploy` purges everything as its last step, once your server answers with the new pages. If the purge fails, the deploy reports it (exit code 1), says why, and the site itself is already deployed: fix the cause and run `cdn:purge --all`. To purge a few pages, for example one that looks stale: ```sh php bin/console cdn:purge blog/my-post /it/chi-siamo # paths on this site (APP_URL) php bin/console cdn:purge https://example.com/blog/my-post # full URLs php bin/console cdn:purge --all # everything ``` Paths are added to `APP_URL`. In development `APP_URL` is your local site, so give the full production URL there (and the production CDN's credentials in `.env`). The CDN keeps one copy per exact URL: `/blog/my-post` and `/it/blog/il-mio-post` are two pages to purge. ### Cloudflare ```sh CDN_PURGE=cloudflare CLOUDFLARE_ZONE_ID=… # on the domain's Overview page CLOUDFLARE_API_TOKEN=… # My Profile → API Tokens → Create Token ``` Create a token with only the **Zone → Cache Purge → Purge** permission, for this zone only: if it ever leaked, it could clear your cache, nothing else. ### Bunny ```sh CDN_PURGE=bunny BUNNY_PULL_ZONE_ID=… # the number in the pull zone's URL in the dashboard BUNNY_API_KEY=… # Account settings → API ``` ### Any CDN with a command ```sh CDN_PURGE=command CDN_PURGE_CMD=bin/purge-cdn ``` The command runs in the project root with the URLs as arguments, or none to purge everything. A script calling your CDN's API or command-line tool is enough: ```sh #!/bin/sh # bin/purge-cdn: purge everything, or the URLs given if [ $# -eq 0 ]; then mycdn purge --all; else mycdn purge "$@"; fi ``` ### Another CDN as a package A package can add a CDN with a class implementing `TinyTank\Cdn\Purger`: ```php use TinyTank\Cdn\Purger; final class FastlyPurger implements Purger { public function __construct(private string $service, #[\SensitiveParameter] private string $token) {} public function name(): string { return 'Fastly'; } public function purgeAll(): void { /* POST /service/{id}/purge_all */ } /** @param list<string> $urls */ public function purge(array $urls): void { /* one purge request per URL */ } } ``` ```php // the package's register() $app->cdn->usePurger(new FastlyPurger(getenv('FASTLY_SERVICE_ID') ?: '', getenv('FASTLY_API_TOKEN') ?: '')); ``` Throw an exception when the CDN refuses, with a message that says why and never contains the token: `deploy` and `cdn:purge` show it. See [Writing a package](../extending/packages). ::: tip Keep tokens on the server CDN tokens are secrets: keep them in the server's `.env` or environment, never in `config/app.php`'s `public` values or in JavaScript. Only `deploy` and `cdn:purge` use them, on the command line. ::: ## Setting up the CDN CDNs read the same `Cache-Control` header, but each has settings that decide whether it does. Check the CDN's current documentation; the gist: * **Cloudflare** doesn't cache HTML pages by default, only files like images and scripts. Add a **Cache Rule** for your site: "Eligible for cache", with the edge TTL taken from the origin's `Cache-Control`. From then on it follows TinyTank's headers. Its "Always Online" option also serves pages while your server is down. * **Bunny**: in the pull zone's caching settings, set the cache expiration to **respect the origin's Cache-Control**, and turn on the **stale cache** options (serve while updating, serve while the origin is offline). * **Others** (Fastly, CloudFront, KeyCDN…) honour `s-maxage` from the origin; look for "stale" or "serve stale" options for the resilience part. Then check a page: `curl -sI https://example.com/about` should show a cache status header such as `cf-cache-status: HIT` (Cloudflare) or `cdn-cache: HIT` (Bunny) on the second request. This is about **pages**. To serve only images and videos from a CDN, see [A CDN for media files](./servers#a-cdn-for-media-files) (`MEDIA_URL`); the two work together. ## Privacy With a CDN in front of the whole site, **every visit goes through the CDN**, so it sees each visitor's IP address and the pages they ask for. That makes it a data processor under the GDPR: * sign its data processing agreement (DPA), and prefer a provider or region in the EU (Bunny is a European company; Cloudflare offers EU options); * mention it in your privacy policy; * check what it logs, and turn off what you don't need: many CDNs keep request logs, and some add analytics or bot-detection scripts and cookies to pages unless you switch them off. TinyTank's own [log](../features/logging) still records nothing about visitors. --- --- url: https://docs.tinytank.dev/1.x/testing.md --- # Testing ```sh npm run build # optional: without it, the tests that check assets are skipped composer test # PHPUnit, your site's tests/ only; in DDEV: ddev composer test composer analyse # PHPStan, level 8 ``` ## Two suites | Suite | Where | What it tests | |---|---|---| | **app** | your site's `tests/` | your site's controllers, routes and templates, with fixture content (`app()`) and its real content (`site()`) | | **framework** | the framework repository's `tests/` | TinyTank itself, against a fixture project and fixture content (see [Contributing](./contributing)) | Your site runs its own suite; the framework's suite runs in the framework repository's CI. ## No web server needed Tests drive the app through `Kernel::handle()`, which takes a Symfony `Request` and returns a `Response`: ```php <?php declare(strict_types=1); namespace App\Tests; final class AboutPageTest extends AppTestCase { public function testAboutPageInItalian(): void { $response = $this->request($this->app(), '/it/about'); self::assertSame(200, $response->getStatusCode()); self::assertStringContainsString('<h1 class="text-3xl font-bold">Chi siamo</h1>', self::body($response)); } } ``` `AppTestCase` (in your `tests/`) extends the framework's `TinyTank\Testing\KernelTestCase` and boots your site with the fixture content in `tests/data/content`, one post per page and a temporary cache directory. The helpers: | Helper | | |---|---| | `$this->app($debug = false, $overrides = [])` | boots the site with the fixture content; overrides merge over `config/app.php` (`AppTestCase`) | | `$this->site($debug = false, $overrides = [])` | the same with the site's real `content/`, for tests of the pages visitors see (`AppTestCase`) | | `$this->bootKernel($root, $debug, $overrides)` | boots any TinyTank app with temporary cache, state, images and log folders (`KernelTestCase`) | | `$this->request($app, $uri, $method, $headers, $body)` | handles a request | | `self::body($response)` | the body of any response, including Datastar streams and files | | `$this->datastarUrl($html, $template, $method)` | the URL of a page's Datastar action rendering `$template` (`@get`, `@post`…; `$method` to pick one) | | `$this->logged()` | what the apps booted in this test have logged (each test gets its own log directory) | | `$this->tempDir()`, `$this->copyToTemp()`, `self::write()` | temporary files, deleted after the test | ## Tests and the Vite build The templates print Vite's asset tags, which come from `public/build/` after `npm run build`. Before the first build, `KernelTestCase` makes pages render without those tags instead of failing, so every test runs on a fresh clone. A test that checks assets declares it, and is skipped until there's a build: ```php public function testThePageScriptLoads(): void { $app = $this->app(); $this->requireViteBuild($app); // skipped, with "run npm run build", when there's no build self::assertStringContainsString('/build/assets/home-', self::body($this->request($app, '/'))); } ``` CI runs `npm run build` before the tests, so these run there. ::: tip A test gets a 500? `$this->app()` boots in production mode, like the live site: an exception becomes the generic error page. Boot with `$this->app(debug: true)` to get the exception itself in the test output, or read what was logged with `$this->logged()`. ::: ## Requests with headers ```php // a Datastar POST from the same site $this->request($app, '/clock', 'POST', ['Sec-Fetch-Site' => 'same-origin'], '{}'); // revalidation $this->request($app, '/about', 'GET', ['If-None-Match' => $etag]); ``` A template action (`datastar.post('_partials/like')` in a page) has a signed URL: take it from the page, then send it with its method and the signals as JSON. Another method gets a 405. ```php $url = $this->datastarUrl(self::body($this->request($app, '/')), '_partials/like', 'post'); $events = self::body($this->request($app, $url, 'POST', ['Sec-Fetch-Site' => 'same-origin'], '{"count":1}')); self::assertStringContainsString('You liked', $events); ``` ## Environment `phpunit.xml.dist` sets `APP_SECRET`, `APP_URL=https://example.test`, `APP_DEBUG=0` and `BLOG_PER_PAGE`, as real environment variables, so your `.env` never leaks into the tests. ## Browser tests PHPUnit checks what the server sends. [Playwright](https://playwright.dev) tests in `tests/e2e/` check what visitors get: the real site in Chromium, served by PHP's built-in server in production mode (`playwright.config.js`). ```sh npm run build npm run test:e2e # in DDEV: ddev exec CHROMIUM_PATH=/usr/bin/chromium npm run test:e2e ``` The skeleton's tests cover: | Spec | Checks | |---|---| | `pages.spec.js` | every URL in the sitemap loads, in both languages; unknown URLs are a 404 | | `datastar.spec.js` | the Datastar demos: search, signed actions, server-sent events, blog filters | | `theme.spec.js` | the system theme, a remembered choice from the first paint (no flash), following the system | | `persist.spec.js` | a persisted signal survives a reload | | `video.spec.js` | nothing reaches YouTube before pressing play (requests to other hosts are recorded, never sent) | | `languages.spec.js` | the switcher and redirects with translated slugs | | `accessibility.spec.js` | the skip link moves the focus to the content, keyboard focus is visible, reduced motion stops movement but keeps colour fades, `motion-allowed` keeps moving | | `no-javascript.spec.js` | colours, the hidden theme switcher and video links without JavaScript | Every test also fails on a **Content Security Policy violation, a JavaScript error or a console error** on any page it visits (`tests/e2e/fixtures.js`), so a new inline script or a blocked resource is caught wherever it appears. Write your own specs with the same fixtures: ```js import { expect, test } from './fixtures.js'; test('the mixer plays', async ({ page }) => { await page.goto('/'); await page.getByRole('button', { name: 'Play' }).click(); await expect(page.getByText('Sound on')).toBeVisible(); }); ``` Playwright needs a Chromium: CI installs its own (`npx playwright install --with-deps chromium`); elsewhere, `CHROMIUM_PATH` points it at an installed one. The framework's own browser helpers (`persist()`, `theme()`, `publicConfig()`) have unit tests with Vitest in the framework repository (`tests/js/`). ## Continuous integration `.github/workflows/ci.yml` runs on every push and pull request: install, the dependency audits, `npm run build`, PHPUnit, PHPStan, then the Playwright browser tests (the [accessibility checks](./accessibility/checking) among them). When a browser test fails, the HTML report with a trace of the failure is attached to the run. The audits check your packages against the published security advisories, and fail the run when one is affected: * `composer audit`: the PHP packages (TinyTank, Symfony, Twig…), any advisory. * `npm audit --audit-level=high`: the JavaScript packages (Vite, Tailwind, Playwright…), high and critical advisories only. Moderate ones appear in the log without failing: they're usually about the build tools on your machine, never the published site. When one fails, the log names the package and the fixed version. Usually `composer update <package>` or `npm update <package>` fixes it; a package pinned by another one (npm's `overrides`, Composer's `conflict`) is the exception. Run the same commands locally to check before pushing. --- --- url: https://docs.tinytank.dev/1.x/security.md --- # Security ## CSRF protection POST, PUT, PATCH and DELETE requests must come from your own site. TinyTank uses Symfony's [`SameOriginCsrfTokenManager`](https://symfony.com/doc/current/security/csrf.html#stateless-csrf-tokens): the browser's `Sec-Fetch-Site` header (or `Origin` / `Referer`) must show the request came from this site, otherwise it gets a **403**. There's no token, no cookie and no session. Every browser sends these headers with `fetch()`, which is how Datastar makes its requests, so nothing needs adding to forms or actions. A route that must accept requests from elsewhere (a webhook, say) can opt out: ```php $app->route(['POST'], '/webhooks/payments', [WebhookController::class, 'handle'], 'webhook', csrf: false); ``` Verify those requests another way, for example with the provider's signature. Behind a reverse proxy, set `APP_TRUSTED_PROXIES` so the check sees the public host and scheme. ## Secrets * Secrets only come from the environment or `.env`, which lives outside the `public/` web root and is never committed. `config/app.php` refuses to boot without `APP_SECRET`. * Vite only inlines variables prefixed `VITE_PUBLIC_` into the bundle, so server variables can't reach the frontend. * Config values reach the browser only through the `public` allowlist in `config/app.php` (`publicConfig()` in JavaScript), and a value containing `APP_SECRET` stops the app from booting. * Variables passed to `datastar.get(…)` are signed but readable: never pass secrets through them. ## Images Published images are re-saved without metadata, so a photo's GPS position, device or time never reaches the site (see [Images](./features/images#privacy-no-metadata)). ## Forms Form posts pass the same-origin check like every POST. Values are cleaned (no control characters, no line breaks in single-line fields, a maximum length), the visitor only ever goes in Reply-To, and spam checks run on this server without third parties (see [Forms](./features/forms#spam-protection)). ## Content * Markdown is rendered with raw HTML escaped and `javascript:` links removed. * Twig escapes all output by default. * JSON-LD is encoded so that `</script>` in any value can't break out of the tag. * Only whitelisted file types in a post folder are ever served or published. * SVGs are served with a script-blocking policy in development; in production, treat SVGs from others as code. ## Responses * Every response sends `X-Content-Type-Options: nosniff`, `Referrer-Policy: strict-origin-when-cross-origin` and `X-Frame-Options: SAMEORIGIN`. * Pages send a strict Content Security Policy (below). * Absolute URLs come from `APP_URL` only, so a forged `Host` header can't poison cached pages. * Production errors are logged, never shown: visitors get a generic error page. The log holds no IP addresses, query strings or function arguments, and is deleted after 14 days ([Logging](./features/logging)). ## Deployment * There's no HTTP endpoint for deployment tasks: cachetool reaches PHP-FPM through its local socket. * The reload command comes from the server's own configuration; keep `.env` writable only by the deploy user. * The cachetool phar is pinned to a version and checked against its SHA-256 hash. ## Content Security Policy Every page tells the browser where it may load things from. By default that's **only your own site**, so even if someone managed to inject markup into a page, the browser would refuse to load their script, send data to their server or frame their page. The default policy: | Directive | Sources | Why | |---|---|---| | `default-src` | `'self'` | anything not listed below: your site only | | `script-src` | `'self' 'unsafe-eval'` + the theme script's hash | your bundles; Datastar evaluates its `data-*` expressions as functions | | `style-src` | `'self'` | your CSS | | `style-src-attr` | `'unsafe-inline'` | `style="…"` attributes (e.g. `display: none` before `data-show` runs); they can't load anything | | `img-src` | `'self' data:` | the icons are SVGs inlined in the CSS | | `font-src`, `connect-src`, `media-src` | `'self'` | | | `object-src` | `'none'` | no plugins | | `base-uri`, `form-action`, `frame-ancestors` | `'self'` | no `<base>` hijacking, forms only post to you, only you may frame your pages | There are no per-request nonces: a nonce makes every response different, which would break ETags and public caching. The one inline script, the theme script, is allowed by its hash, which never changes. The JSON blocks (`public_config()`, JSON-LD) are data, not scripts, so the policy doesn't apply to them. While the Vite dev server runs (debug mode), its origin and WebSocket are allowed too. With `MEDIA_URL` set, its host is allowed in `img-src` and `media-src`. ### Allowing other hosts When a feature needs another host (a video player, analytics, a CDN), add it to the directive it needs in `config/app.php`: ```php 'csp' => [ 'enabled' => true, 'report_only' => false, 'sources' => [ 'frame-src' => ['https://www.youtube-nocookie.com'], 'media-src' => ['https://cdn.example.com'], ], ], ``` or from `config/bootstrap.php`: ```php $app->csp->allow('script-src', 'https://plausible.io')->allow('connect-src', 'https://plausible.io'); ``` A directive the policy doesn't list yet (like `frame-src`) starts from `'self'`. Unknown directives and sources containing spaces, `;` or `,` are refused, so a typo can't silently break the policy. To try a change without breaking anything, set `report_only` to `true`: browsers then only report what they would block, in the developer console. A controller can send its own `Content-Security-Policy` header for one page; TinyTank then leaves it alone. ### Sources for one page Components can allow a source on the page they appear on with `{% do csp_allow('frame-src', '…') %}` (see [Content components](./content/components#allowing-sources-for-a-component)). The built-in video components do this for their player, so `frame-src` lists YouTube or Vimeo only on pages that show a video. Everything else keeps the site's policy. ### Inline scripts from Datastar `execute_script()` runs its code as an inline `<script>`, which the policy blocks. Allow each script by its exact code: ```php $app->csp->allowScript("console.log('updated')"); ``` Patching elements and signals needs nothing in the policy, so prefer those. ## Reporting a vulnerability Please report security problems privately, not in a public issue: the framework repository's **Security** tab → [Report a vulnerability](https://github.com/tinytankphp/framework/security/advisories/new). See its [security policy](https://github.com/tinytankphp/framework/blob/main/SECURITY.md). --- --- url: https://docs.tinytank.dev/1.x/contributing.md --- # Contributing TinyTank is three repositories: | Repository | What it is | |---|---| | [tinytankphp/tinytank](https://github.com/tinytankphp/tinytank) | the site skeleton: the starting point for every site | | [tinytankphp/framework](https://github.com/tinytankphp/framework) | the framework package, `tinytank/framework` | | [tinytankphp/docs](https://github.com/tinytankphp/docs) | this documentation (VitePress) | ## Working on all three together Changes often span the framework, the skeleton and the docs. Clone the other two repositories **inside** the skeleton. `packages/*` is gitignored and `docs/` is excluded in your clone only (`.git/info/exclude`, so sites made from the skeleton don't inherit it): neither is ever published with it: ```sh git clone git@github.com:tinytankphp/tinytank.git && cd tinytank git clone git@github.com:tinytankphp/framework.git packages/tinytank git clone git@github.com:tinytankphp/docs.git docs printf '/docs/\n/sites/\n' >> .git/info/exclude # this clone only ddev start ddev composer update tinytank/framework # symlinks packages/tinytank into vendor/ ``` The skeleton's `composer.json` lists a path repository (`packages/*`) before the framework's GitHub repository. When `packages/tinytank` exists, Composer prefers it and symlinks it into `vendor/tinytank/framework`, so framework edits take effect immediately. Because of that, the skeleton never commits `composer.lock`. Each clone is its own git repository: commit framework changes in `packages/tinytank`, docs changes in `docs/`, skeleton changes at the root. ## Running the checks ```sh ddev composer test && ddev composer analyse # skeleton (app tests) cd packages/tinytank && composer update && composer test && composer analyse # framework cd docs && npm install && npm run build # docs ``` The docs dev server (`npm run dev` in `docs/`) runs on port 5174; DDEV exposes it at `https://<project>.ddev.site:5174`. ## Guidelines * Keep the framework free of `App\` code: what a site might change belongs in the skeleton, or needs an extension point in the framework. * Every behaviour change comes with a test (framework or app suite) and a docs update. * Prefer proven libraries for infrastructure; TinyTank's own code is the glue between them. * PHPStan level 8 stays clean in both PHP repositories. ## Docs fixes Every page has an **Edit this page on GitHub** link: small fixes can go straight to the docs repository as a pull request. --- --- url: https://docs.tinytank.dev/1.x/reference/config.md --- # Configuration reference Every key of `config/app.php`. See [Configuration](../basics/configuration) for how settings and environment variables fit together. | Key | Type | Default in `config/app.php` | Description | |---|---|---|---| | `secret` | string | `APP_SECRET` (required) | Signs Datastar template URLs | | `debug` | bool | `APP_DEBUG === '1'` | Development mode: no caches, drafts visible, exception pages | | `url` | string | `APP_URL` (required, validated) | Public base URL, no trailing slash. Used for every absolute URL | | `media_url` | string | `MEDIA_URL` or `''` | Where post and page files and video posters are served from: `''` (this site) or a CDN's `https://` base URL | | `images.widths`, `images.sizes` | list, string | `[480, 960, 1440]`, `'(min-width: 48rem) 48rem, 100vw'` | Responsive image widths and how wide images are shown ([Images](../features/images)); also `images.presets`, `images.formats`, `images.quality` | | `mailer.dsn`, `mailer.from` | ?string | `MAILER_DSN`, `MAILER_FROM` | Sending email for [forms](../features/forms) | | `log.level` | string | `LOG_LEVEL`, or `debug` in development and `info` in production | The least important messages written to the [log](../features/logging) | | `log.days` | int | `14` | Daily log files to keep | | `log.alert_to` | ?string or list | `LOG_ALERT_TO` | Who gets an email when an error is logged (needs the mailer) | | `log.pushover` | `{token, user}` | `PUSHOVER_TOKEN`, `PUSHOVER_USER` | Push alerts through Pushover when an error is logged; both or neither ([Push alerts](../features/logging#push-alerts)) | | `log.path` | string | `var/log/app.log` | The log file (dated per day), or a stream like `php://stderr` | | `cdn.enabled` | bool | `CDN_CACHE=1`, else off | Cache pages at a CDN ([CDN caching](../deployment/cdn)) | | `cdn.ttl` | ?int | an hour with purging, else 5 minutes | How long the CDN keeps a page (`s-maxage`) | | `cdn.stale_while_revalidate`, `cdn.stale_if_error` | int | `60`, `86400` | Seconds the CDN may serve an old copy while refreshing it, or while the site is down | | `cdn.exclude` | list | `[]` | Route names never cached at the CDN (the Datastar endpoint never is) | | `cdn.purge` | ?string | `CDN_PURGE` | `cloudflare`, `bunny` or `command`; with `cdn.cloudflare` (`zone`, `token`), `cdn.bunny` (`pull_zone`, `key`), `cdn.command` | | `trusted_proxies` | list | from `APP_TRUSTED_PROXIES` | Reverse proxies whose `X-Forwarded-*` headers are trusted | | `language` | string | `'en'` | The default language (no URL prefix) | | `languages` | map | `en`, `it` | `code => ['name' => …, 'locale' => …]`; codes like `en` or `pt-br` | | `blog.per_page` | int | `BLOG_PER_PAGE` or `20` | Posts per page on `/blog` | | `public` | map | `[]` | Values page scripts may read through `publicConfig()`; an allowlist, refused if a value contains `APP_SECRET` | | `csp.enabled` | bool | `true` | Send the Content Security Policy header on pages | | `csp.report_only` | bool | `false` | Report violations in the browser console instead of blocking | | `csp.sources` | map | `[]` | Extra sources per directive, e.g. `['frame-src' => ['https://player.vimeo.com']]` | | `theme.default` | string | `'system'` | What visitors without a saved choice get: `'system'`, `'light'` or `'dark'` ([theme](../features/theme#a-default-other-than-the-system)) | | `site.name` | string or map | `'TinyTank'` | Site name: titles, Open Graph, feed | | `site.description` | string or map | | Default meta description and feed subtitle | | `site.image` | ?string or map | `null` | Default share image (`/path` or URL) | | `site.author` | ?string or map | `null` | Author for posts and the feed; defaults to the site name | Each `site` value can be a map `language => value` instead, see [Languages](../features/languages#the-site-s-name-description-and-share-image). ## `config/collections.php` Data collections and their fields: `name => ['fields' => […], 'sort' => …, 'fallback' => …, 'json' => …]`. See [Data collections](../content/collections). ## `config/forms.php` Forms and their fields, recipients and spam checks: `name => ['fields' => […], 'to' => …, 'subject' => …, 'reply_to' => …, 'spam' => […]]`. See [Forms](../features/forms). ## `config/globals.php` Optional: values for every template, as `globals` (and `$app->globals` in PHP). Returns an array, nested as deep as you like. Public: no secrets. See [Global values](../basics/templates#global-values). ## Overrides `Kernel::boot($root, $debug, $overrides)` merges `$overrides` over the file. These extra keys are only meant for overrides (mostly in tests): | Key | Default | | |---|---|---| | `content_dir` | `<root>/content` | where `blog/` and the collection folders live | | `cache_dir` | `<root>/var/cache` | where compiled caches are written | | `collections` | `config/collections.php` | collection definitions, instead of the file | | `forms` | `config/forms.php` | form definitions, instead of the file | | `globals` | `config/globals.php` | template globals, instead of the file | | `images_dir` | `<root>/var/images` | where encoded images are kept (tests use a temporary folder) | | `state_dir` | `<root>/var/state` | what's kept across deploys: the forms' rate limits (tests use a temporary folder) | --- --- url: https://docs.tinytank.dev/1.x/reference/environment.md --- # Environment variables Set them as real environment variables on servers, or in `.env` (real variables win). `.env.example` lists them all. | Variable | Required | Default | Description | |---|---|---|---| | `APP_SECRET` | yes | | Signs Datastar template URLs. Generate with `openssl rand -hex 32` | | `APP_URL` | yes | | Public base URL, no trailing slash, e.g. `https://example.com` | | `APP_DEBUG` | no | off | `1` = development mode | | `MAILER_DSN` | for forms | | How email is sent (Symfony Mailer), e.g. `smtp://user:pass@smtp.example.com:587` | | `MAILER_FROM` | for forms | | The address emails come from, of your own domain | | `CONTACT_TO` | for the contact form | | Where the skeleton's contact form goes (comma-separated) | | `CDN_CACHE` | no | off | `1` = cache pages at the CDN ([CDN caching](../deployment/cdn)) | | `CDN_PURGE` | no | | How to purge the CDN: `cloudflare`, `bunny` or `command` | | `CLOUDFLARE_ZONE_ID`, `CLOUDFLARE_API_TOKEN` | for Cloudflare purging | | The zone, and a token with only the Cache Purge permission | | `CLOUDFLARE_API_TOKEN`, `CLOUDFLARE_ACCOUNT_ID` | for `publish:static` | | A token with the Workers permissions, and its account ([Publishing](../static-site-generator/publishing)). A static site has no CDN purging, so the name is free | | `SMTP_HOST`, `SMTP_PORT`, `SMTP_USER`, `SMTP_PASSWORD` | for static forms sent over SMTP | `SMTP_PORT` 465 | Your mail server, set as the Worker's secrets by `publish:static` ([Forms](../static-site-generator/forms)). Passwords in single quotes | | `BUNNY_PULL_ZONE_ID`, `BUNNY_API_KEY` | for Bunny purging | | The pull zone's number and the account's API key | | `CDN_PURGE_CMD` | for `command` purging | | A command run with the URLs as arguments, none for everything | | `LOG_ALERT_TO` | no | | Email errors to this address (comma-separated for several), see [Logging](../features/logging) | | `PUSHOVER_TOKEN`, `PUSHOVER_USER` | no | | Push alerts through [Pushover](https://pushover.net): errors on the PHP site, a form that couldn't be sent on a static one. The application's token and your user key, both or neither ([Push alerts](../features/logging#push-alerts)) | | `LOG_LEVEL` | no | `debug` / `info` | The least important messages logged: `debug`, `info`, `notice`, `warning`, `error`… | | `MEDIA_URL` | no | | Serve post and page files and video posters from a CDN: an `https://` base URL, no trailing slash | | `BLOG_PER_PAGE` | no | `20` | Posts per page on `/blog` | | `APP_TRUSTED_PROXIES` | no | | Comma-separated IPs/CIDRs of trusted proxies, or `REMOTE_ADDR` | | `APP_OPCACHE` | no | `cachetool` | How `deploy` refreshes Opcache: `cachetool`, `reload` or `none` | | `APP_FPM_SOCKET` | no | `/run/php-fpm.sock` | PHP-FPM socket or `host:port`, for cachetool | | `APP_CACHETOOL` | no | `cachetool` | The cachetool binary | | `APP_OPCACHE_RELOAD_CMD` | no | | The command for `reload` mode, e.g. `sudo systemctl reload php8.4-fpm` | Frontend code only ever sees variables prefixed `VITE_PUBLIC_` (none by default). --- --- url: https://docs.tinytank.dev/1.x/reference/console.md --- # Console commands ```sh php bin/console list # in DDEV: ddev console list ``` ## `deploy` Checks the site, optimizes the autoloader, builds every cache and the published files aside, then switches the site to them and refreshes the web server's Opcache. See [Deploying](../deployment/) for the options and [Deploy steps](../extending/deploy-steps) for the steps. ```sh php bin/console deploy [--list-steps] [--skip=a,b] [--assets] [--opcache=cachetool|reload|none] [--fcgi=…] [--cachetool=…] [--reload-cmd=…] [--composer=…] [--no-dev] [--skip-composer] [--skip-opcache] [--rollback] ``` Exit codes: `0` deployed, `1` a step failed (the live site is as it was, unless the failing step came after `switch`), `2` invalid options (nothing was changed). `--rollback` puts the previous build back. ## `check` Checks the server and the site are ready to deploy, without changing anything: PHP and its extensions, the image library, `APP_SECRET` and `APP_URL`, writable folders, content, templates, pages hidden by routes, the Vite build. `deploy` runs it first. See [Checking first](../deployment/#checking-first). | Option | | |---|---| | `--json` | the results as JSON: `{"ok": true, "checks": [{"check", "status", "message"}…]}` | Exit codes: `0` no errors (warnings allowed), `1` errors. ## `cache:clear` Deletes everything in `var/cache` (keeping `.gitkeep`) and `var/deploy`, and the post, page and collection files published to `public/media/blog/`, `public/media/pages/` and `public/media/collections/`. If a deploy left the Composer autoloader authoritative, it also runs `composer dump-autoload`, so new classes are found again. Run it when you go back to development after a deploy. | Option | Default | | |---|---|---| | `--composer` | `composer` | Composer binary | ## `site:clean` Removes the skeleton's examples ([Starting a site](../getting-started/checklist#_3-the-starter-content)): the files and folders listed in `.examples`, and every block between a line containing `example:start` and one containing `example:end` in the site's `config/`, `src/`, `templates/`, `resources/`, `tests/`, `translations/`, `content/`, `public/` and `AGENTS.md`, then `.examples`. It lists everything first and asks. Unbalanced markers stop it before anything changes. While `.examples` exists, `deploy` warns that the examples are still there. | Option | | |---|---| | `--dry-run` | only list what would go | | `--force`, `-f` | don't ask | ## `build:static` Also `static:build`, so the static commands group together in `bin/console list static`. Renders the whole site into plain files for a static host ([Static Site Generator](../static-site-generator/)). | Option | | |---|---| | `--out` | the output folder (default `static.out`, or `deploy`) | | `--base-url` | the published site's address (default `static.base_url`, or `APP_URL`) | | `--host` | `cloudflare` (default), `none`, or a `HostAdapter` class | | `--allow-dynamic` | succeed even when pages use what needs the server (listed as a warning) | Exit codes: `0` built, `1` broken links, pages that need the server, or the host's limits, `2` wrong options. ## `preview:static` Also `static:preview`, so the static commands group together in `bin/console list static`. Serves the static build locally, as its host will: Cloudflare's local server for the `cloudflare` host, or PHP's with `--php`. Options: `--port` (4173), `--ip` (`0.0.0.0`), `--out`, `--php`, `--dry-run`. See [Preview](../static-site-generator/preview). ## `publish:static` Also `static:publish`, so the static commands group together in `bin/console list static`. Builds the static site and publishes it on Cloudflare Workers (`wrangler deploy`), with `CLOUDFLARE_API_TOKEN` and `CLOUDFLARE_ACCOUNT_ID` from `.env`; forms sent over SMTP get the `SMTP_*` keys as the Worker's secrets. Options: `--no-build`, `--dry-run`. See [Publishing](../static-site-generator/publishing). Exit codes: `0` published, `1` the build or wrangler failed, `2` missing settings. ## `cdn:purge` Drops pages from the CDN's cache ([CDN caching](../deployment/cdn)), with the purger set by `CDN_PURGE` or a package. ```sh php bin/console cdn:purge blog/my-post /it/chi-siamo # paths on this site (APP_URL) php bin/console cdn:purge https://example.com/blog/my-post # full URLs php bin/console cdn:purge --all # everything ``` Exit codes: `0` purged, `1` the CDN refused or no purge is set up (the message says why), `2` no URLs and no `--all`, or both. ## Your commands Every command class in `src/Command/` is registered automatically. See [Console commands](../extending/commands). --- --- url: https://docs.tinytank.dev/1.x/reference/twig.md --- # Twig reference ## Globals | Global | Type | | |---|---|---| | `site` | `TinyTank\Site` | `site.name`, `site.description` (in the current language), `site.baseUrl`, `site.language`, `site.locale`, `site.defaultLanguage`, `site.languages`, `site.path` (the current page's path without the language prefix, for menus: `site.path starts with '/projects'`) | | `seo` | `TinyTank\Seo\Seo` | page metadata setters: `{% do seo.title('…') %}` (see [SEO](../features/seo)) | | `datastar` | `TinyTank\Datastar` | Datastar actions, below | | `globals` | `array` | your own values from `config/globals.php` (empty without it): `globals.socials.github` (see [Global values](../basics/templates#global-values)) | Plus anything your `config/bootstrap.php` adds. ## Functions | Function | Returns | |---|---| | `video(provider, id, start = 0)` | for video components: `{provider, name, id, title, poster, player, src, url}`; allows the player in this page's `frame-src` | | `csp_allow(directive, source, …)` | adds Content Security Policy sources to the current response only (use with `do`) | | `image(url, alt = '', options = {})` | a `<picture>` with responsive AVIF/WebP versions for a post's or page's image, a plain `<img>` otherwise; options: `preset`, `loading`, `sizes`, any `<img>` attribute | | `form_spam(form)` | the spam checks' hidden fields for a form, inside its `<form>`; makes the page uncacheable when it prints a timing token | | `content(item)` | the item's HTML with its content components rendered (`entry` = the item). It stays HTML in a variable: `{% set body = content(post) %}{{ body }}` | | `posts()` | a `TinyTank\Query` over the blog posts ([Querying content](../basics/querying)) | | `pages()` | a `TinyTank\Query` over the content pages | | `collection(name)` | a `TinyTank\Query` over a data collection | | `path(name, params = {}, language = null)` | URL path of a named route, in the current (or given) language | | `absolute_url(pathOrUrl)` | absolute URL from `APP_URL`; absolute `http(s)` URLs are returned unchanged | | `t(message, params = {}, language = null)` | translated text | | `vite(entry, …)` | `<link>`/`<script>` tags for Vite entry points (dev server or build); entries or lists of entries | | `vite_preload(source, …)` | `<link rel="preload">` for built fonts and images, by source path (e.g. a Fontsource `.woff2`); nothing with the dev server | | `theme_script()` | inline `<script>` setting `<html data-theme>` from the saved choice or the system setting; first in `<head>` | | `public_config()` | `<script type="application/json" id="tinytank-config">` with config `public`, or nothing when empty | | `seo_tags()` | the page's `<title>`, meta, canonical, Open Graph, Twitter, hreflang and JSON-LD | | `language_switcher()` | list of `{code, name, url, active, available}` for the current page | | `signal(name, default = '', max = 1000)` | Datastar: a signal the request sent, as text ([Reading signals](../basics/datastar#reading-signals)) | | `signal_int(name, default = 0, min = null, max = null)` | a signal as a whole number, within `min` and `max` | | `signal_bool(name, default = false)` | a signal as `true`/`false` | | `signal_enum(name, choices, default = first)` | a signal that must be one of `choices` | | `patch_signals(signals, options = {})` | Datastar: queue a signals patch (use with `do`) | | `remove_elements(selector, options = {})` | Datastar: queue an element removal | | `execute_script(script, options = {})` | Datastar: queue a script | | `location(uri, options = {})` | Datastar: queue a redirect | ## Filters | Filter | | |---|---| | `t(params = {}, language = null)` | `{{ 'Hello {name}'\|t({name: user}) }}` | | `patch_elements(options = {})` | Datastar: queue the content as an elements patch (`{% apply patch_elements %}…{% endapply %}`) | | `format_date`, `format_datetime`, `format_time`, `format_number`, `format_currency`, … | from [Twig Intl Extra](https://twig.symfony.com/doc/3.x/filters/format_date.html); pass `locale: site.locale` | ## `datastar` | Method | Prints | |---|---| | `datastar.get(template, vars = {}, options = {})` | `@get(…)` rendering `template` with `vars` (also `post`, `put`, `patch`, `delete`) | | `datastar.action(method, url, options = {})` | `@method(url, options)` for any URL | `options` are Datastar's own action options, e.g. `{openWhenHidden: true}`. Templates rendered by Datastar requests receive the browser's signals as `signals`. --- --- url: https://docs.tinytank.dev/1.x/reference/php.md --- # PHP API The public API of the classes a site uses, from the `tinytank/framework` package (`vendor/tinytank/framework/src/`, namespace `TinyTank\`). ## Kernel `TinyTank\Kernel`, available as `$this->app` in controllers, `$this->app()` in commands, and as the argument of `config/routes.php` and `config/bootstrap.php`. | Member | | |---|---| | `Kernel::boot(string $root, ?bool $debug = null, array $overrides = [])` | builds the app from `config/` | | `Kernel::serve(string $root)` | `public/index.php`: boots the app and answers the request; if it can't start, a plain 500 page and the reason in PHP's log (rethrown with `APP_DEBUG=1`) | | `run()` | handles the current HTTP request (`public/index.php`) | | `handle(Request $request): Response` | handles any request; used by tests | | `get(path, handler, name, requirements, priority = 0)`, `post(…)` | add a route | | `route(methods, path, handler, name, requirements, csrf = true, priority = 0)` | add a route; higher priority is tried first | | `path(name, params = [], language = null): string` | URL path in the current language; for the `page` and `blog_post` routes, pass the folder path / slug and it writes the language's translated URL | | `t(message, params = [], language = null): string` | translate a UI text | | `posts(): Query`, `pages(): Query`, `collection(name): Query` | content queries ([Querying content](../basics/querying)) | | `shadowedPages(): array` | content pages another route hides: `path => route name` (`deploy` refuses to run with any) | | `render(template, vars = []): string` | render a Twig template | | `content(item, ?link): string` | an item's HTML with its components rendered; with `$link`, components become links (the feed) | | `cspAllow(directive, ...sources)` | CSP sources for the current response only | | `video(provider, id, start = 0): array` | a video's poster, title and player URL; allows the player for this response | | `$embeds` | `TinyTank\Content\Embeds`: `check()`, `video()`, `fetch()`, `missing()` | | `addTemplates(dir, ?namespace)` | add a package's templates after the site's, before the framework's | | `Kernel::TEMPLATES` | the framework's default templates folder (`@tinytank/…`) | | `stream(template, vars = []): StreamedResponse` | render a template as a Datastar response | | `error(status, message, headers = []): Response` | an error page | | `request(): Request` | the current request | | `addDeployStep(name, step, description, before, after)` | add a step to `deploy` | | `$root`, `$debug`, `$cacheDir`, `$stateDir` | project root, debug mode, cache directory, what's kept across deploys (`var/state/`) | | `$twig`, `$router`, `$blog`, `$seo`, `$site`, `$container`, `$translations`, `$datastar`, `$vite`, `$publicConfig`, `$csp`, `$collections`, `$pages` | TinyTank's services | | `$cdn` | CDN caching and purging: `skip()` keeps the current response out of the CDN, `usePurger()`, `purger()`, `url()` ([CDN caching](../deployment/cdn)) | | `signals(): Signals` | the current Datastar request's signals, read with their type: `string()`, `int()`, `bool()`, `enum()`, `has()`, `all()` ([Reading signals](../basics/datastar#reading-signals)) | | `noStore()` | the current response is for one visitor: `Cache-Control: no-store, private`, no ETag, never at a CDN ([Not at the CDN, or nowhere](../deployment/cdn#not-at-the-cdn-or-nowhere)) | | `$logger` | the log, a Monolog `Logger` (PSR-3); also `Psr\Log\LoggerInterface` in the container ([Logging](../features/logging)) | ## Controller `TinyTank\Controller`, base class for app controllers. See [Controllers](../basics/controllers). `render()`, `stream()`, `json()`, `notFound()`, `path()`, `t()`, `get()`, `request()`, `signals()`, and `$this->app`. ## HttpError `throw new TinyTank\HttpError(403, 'Not allowed.')` from a handler: the kernel answers with that status's error page (in debug mode too), the message translated. 4xx and 5xx only; the message is shown to the visitor, so keep it short and generic. ## Site `TinyTank\Site` (`$app->site`, `site` in Twig). | Member | | |---|---| | `name(?language)`, `description(?language)`, `image(?language)`, `author(?language)` | from `config/app.php`, in the current (or given) language | | `$baseUrl` | `APP_URL` | | `$defaultLanguage`, `$languages` | language configuration | | `language(): string`, `locale(): string` | the current language and locale | | `prefix(?language): string` | `''` for the default language, `'/it'` otherwise | | `localize(path, ?language): string` | `'/blog'` → `'/it/blog'` | | `url(pathOrUrl): string` | absolute URL from `APP_URL` | | `switcher(): array` | the current page in every language | | `setAlternates(array $alternates, array $fallbacks = [])` | declare where the current page exists | | `alternates(): array` | `language => path` of the current page | ## Seo `TinyTank\Seo\Seo` (`$app->seo`, `seo` in Twig). Fluent setters `title()`, `description()`, `canonical()`, `image()`, `type()`, `noindex()`, `article()`, `schema()`; plus `url()`, `canonicalUrl()`, `imageUrl()`, `pageTitle()`, `documentTitle()`, `render()`. See [SEO](../features/seo). ## Blog Query posts with `$app->posts()` ([Querying content](../basics/querying)). `TinyTank\Blog\Blog` (`$app->blog`) is the source behind it: compiling, caching and files. | Method | | |---|---| | `query(): Query` | what `$app->posts()` returns | | `items(?language): array` | every post in a language, `slug => post`, newest first | | `translations(slug): list` | the languages a post exists in | | `uri(slug, language): ?string` | a post's URL segment in a language (a translated slug or the folder name) | | `asset(slug, file): ?string` | the path of a post's published file | | `warmup()`, `publishAssets(publicDir)` | used by `deploy` | | `$perPage` | posts per page (`blog.per_page`) | A post is an array: | Field | | |---|---| | `slug` | the folder name: the post's identity in every language | | `uri` | the URL segment in this language (`slug:` in a translation, or the folder name) | | `language`, `title`, `summary` | strings | | `date`, `updated` | `YYYY-MM-DD` (`updated` may be `null`) | | `image` | public URL or `null` | | `tags` | list of strings | | `draft` | bool | | `reading_minutes` | int | | `html` | the rendered post (safe to print raw) | | `source` | e.g. `2026/09/hello-tinytank/index.md` | | `assets` | publishable files in the post folder | `TinyTank\Blog\PostSeo::apply($seo, $post)` maps a post onto the page metadata. ## Pages Query pages with `$app->pages()` ([Content pages](../content/pages)). `TinyTank\Pages\Pages` (`$app->pages`) is the source behind it. | Member | | |---|---| | `query(): Query` | what `$app->pages()` returns | | `items(?language): array` | every page in a language, `path => page` | | `translations(path): list` | the languages a page exists in | | `uri(path, language): ?string` | a page's URL path in a language, translated slugs included | | `asset(file): ?string` | the path of a page's published file (`about/team.jpg`) | | `warmup()`, `publishAssets(publicDir)` | used by `deploy` | | `Pages::PATH`, `Pages::ASSET_URL` | the page route's requirement, `/media/pages` | `TinyTank\Pages\PageSeo::apply($seo, $page)` maps a page onto the page metadata. ## Collections `TinyTank\Collections\Collections` (`$app->collections`), see [Data collections](../content/collections). | Member | | |---|---| | `query(name): Query` | what `$app->collection(name)` returns (unknown names throw) | | `json(name, ?language): list` | the allowlisted fields served at `/data/<name>.json` | | `schema(name): Schema` | a collection's definition | | `warmup(): array` | compile into `var/cache/collections.php`; returns items per collection | | `exported(): list<string>` | collections with a JSON export | | `asset(file): ?string` | the file behind `projects/pulse-os/cover.jpg` (an item folder's), or null | | `publishAssets(publicDir): int` | copy the item folders' files to `public/media/collections/` (deploy does) | | `Collections::ASSET_URL` | `/media/collections` | ## Images `TinyTank\Images\Images` (`$app->images`), see [Images](../features/images): `picture()`, `variant()`, `original()`, `publish()`, `size()`, `widthsFor()`; `$widths`, `$formats`, `$sizes`. `$app->image($url, $alt, $options)` is what `image()` prints. ## Forms `TinyTank\Forms\Forms` (`$app->forms`), see [Forms](../features/forms). | Member | | |---|---| | `submit(name, Request): Submission` | validates, runs the spam checks, sends the email | | `get(name): Form`, `blank(name): Submission` | a form's definition; its empty state | | `rule(form, field, Closure)` | a custom validation rule | | `addSpamCheck(name, Closure $factory)` | a spam check forms can list in `spam` | | `spamMarkup(name): string` | what `form_spam()` prints | | `useTransport(TransportInterface)` | deliver through another transport (tests) | `Submission`: `$values`, `$errors` (field or `_form` => message), `$sent`, `$spam` (the reason, for logs), `valid()`. ## Csp `TinyTank\Csp` (`$app->csp`), the Content Security Policy sent on pages (see [Security](../security#content-security-policy)). | Member | | |---|---| | `allow(directive, ...sources): self` | add sources, e.g. `allow('frame-src', 'https://player.vimeo.com')` | | `allowScript(code): self` | allow one inline script by its hash (for `execute_script()`) | | `Csp::hash(code): string` | `'sha256-…'` source for inline code | | `directives(): array` | the policy, `directive => sources` | | `header(?devServer): string` | the header value | | `$enabled`, `$reportOnly` | from `config/app.php` `csp` | ## Container `TinyTank\Container` (`$app->container`), PSR-11: `set(id, factoryOrValue)`, `get(id)`, `has(id)`. ## Console * `TinyTank\Console\AppCommand`: base class for commands; `app()`, `root()` * `TinyTank\Console\Console::run($root)`: what `bin/console` calls ## Testing `TinyTank\Testing\KernelTestCase`, the base class for app tests (needs `phpunit/phpunit`): `bootKernel()`, `request()`, `body()`, `tempDir()`, `copyToTemp()`, `write()`, and `requireViteBuild($app)` for tests that check built assets. `request()` takes form fields as `parameters:`. See [Testing](../testing). --- --- url: https://docs.tinytank.dev/1.x/deployment/static.md --- # Static builds Static builds have their own section now: [Static Site Generator](../static-site-generator/). | Was | Now | |---|---| | How it works, Broken links | [How it works](../static-site-generator/how-it-works) | | Configuration | [Configuration](../static-site-generator/configuration) | | Hosts, Your own host | [Hosts](../static-site-generator/hosts) | | Publishing | [Publishing](../static-site-generator/publishing) | | What needs the server | [What needs the server](../static-site-generator/what-needs-the-server) | | Search | [Search](../static-site-generator/search) | | Forms | [Forms](../static-site-generator/forms) | | Preview | [Preview](../static-site-generator/preview) |