# Taphra > Full-stack PHP for the agent era: a framework for PHP 8.2 and later with routing, controllers and views, DataStores for SQL databases, auth, queues, email, localisation, billing, AI providers, an agent loop and an MCP server, in one Composer package. Version 1.1.0, MIT licence. Start a project with `composer create-project taphra/skeleton my-app` (or `taphra/api-starter`, `taphra/ai-chat`, `taphra/mcp-server`). Each starter has an `AGENTS.md` with the app's layout, commands and safety rules. Taphra is not Laravel or Symfony: do not assume their APIs. In an app, the installed framework source is in `vendor/taphra/taphra/` (the core in `taphra/src/`, the packages in `packages//src/`), and it is short enough to read. --- Source: https://taphra.dev/docs/ # Taphra documentation These guides cover Taphra 1.x for PHP 8.2 and later, in the order you are likely to need them. Each page covers one topic and links to the others where they meet. Examples use the layout of the `taphra/skeleton` starter. ## Start here 1. [Getting started](getting-started.md): requirements, installing a new app, the skeleton's layout, a first page and a first JSON endpoint. 2. [Configuration and environments](configuration.md): the YAML files, environment sections, `APP_ENV`, secrets and the settings that matter in production. ## Building an app 3. [Routing and controllers](routing.md): `routes.yml`, named routes, route groups and middleware, routes from packages, controller actions and their helpers. 4. [Views and helpers](views.md): templates, layouts, elements, escaping, forms and the HTML helpers. 5. [Requests and validation](requests.md): reading input, uploads, the validator and form requests. 6. [REST APIs](rest-apis.md): JSON controllers, CRUD controllers, API resources and OpenAPI output. ## Data 7. [Database](database.md): connections, migrations (from more than one folder), foreign keys, seeders and factories, transactions, and which query API to use. 8. [DataStores](datastores.md): one class per table, the query builder, casts, relations, scopes, hooks and pagination. 9. [SqlQuery](SqlQuery.md): the query builder for joins, sub-queries, CTEs, window functions, upserts and raw SQL with bindings. ## Security 10. [Authentication](authentication.md): sessions, remember-me, password hashing, JWT, two-factor codes and policies. 11. [Security](security.md): CSRF, cookies and sessions, escaping, encryption, rate limiting, the defaults, and a production checklist. ## AI 12. [AI](ai.md): providers, streaming, structured output, tools and the agent loop, conversations and prompt templates. 13. [MCP server](mcp.md): exposing tools, resources and prompts to MCP clients over stdio and HTTP. 14. [AI builder](ai-builder.md): `ai:build`, `ai:fix` and `ai:rollback` (a preview feature). ## Application services 15. [Queues](queues.md): jobs, drivers and workers. 16. [Cache](cache.md): cache drivers, the cache API and locks. 17. [Events](events.md): emitting and listening to events. 18. [Scheduler](scheduler.md): recurring tasks from one cron entry. 19. [Email](email.md): transports, templates with placeholders, attachments, and sending from a queue job. 20. [Localisation](localisation.md): translations, plural rules, the locale middleware and `lang:scan`. 21. [Billing](billing.md): customers, subscriptions and webhooks with Stripe. ## Architecture 22. [Service container and providers](container.md): bindings, autowiring and service providers. 23. [Logging and debugging](logging.md): log drivers and levels, request IDs, the request log and the REPL. ## Testing and operations 24. [Testing](testing.md): in-process HTTP tests (JSON, HTML pages and redirects, raw bodies), a database in tests and faking AI providers. 25. [Command line](cli.md): every `php taphra` command. 26. [Deployment](deployment.md): php-fpm, FrankenPHP worker mode, `php taphra optimize`, workers and cron. 27. [Upgrading](upgrading.md): the version policy, upgrade notes ([1.0.0 to 1.0.1](upgrade/1.0.0-1.0.1.md), [1.0.1 to 1.0.2](upgrade/1.0.1-1.0.2.md), [1.0.2 to 1.1.0](upgrade/1.0.2-1.1.0.md)) and moving from pre-release copies to 1.0. ## Tutorials Step-by-step builds of small apps: - [Hello world](tutorials/01-hello-world.md) - [A REST API](tutorials/02-rest-api.md) - [An AI chatbot](tutorials/03-ai-chatbot.md) - [An MCP server](tutorials/04-mcp-server.md) - [An agent with tools](tutorials/05-agent-with-tools.md) ## Reference - [How Taphra compares](framework-comparison.md) with Laravel, Symfony and others. - [Changelog](../CHANGELOG.md). - The bundled libraries, usable without the framework: [db](../packages/db/README.md), [validator](../packages/validator/README.md), [container](../packages/container/README.md), [crypt](../packages/crypt/README.md), [l10n](../packages/l10n/README.md), [ai](../packages/ai/README.md), [billing](../packages/billing/README.md). Found a mistake in these pages? Open an issue or a pull request; [CONTRIBUTING.md](../CONTRIBUTING.md) explains how. --- Source: https://taphra.dev/docs/introduction/ # Taphra **Full-stack PHP for the agent era. AI and MCP included.** Taphra is a full-stack framework for PHP 8.2 and later: routing, controllers and views, a database layer, authentication, queues, email, localisation and billing, plus AI providers, a tool-use agent loop and an MCP server, installed as one Composer package. It runs on ordinary PHP hosting with safe defaults, and its code is explicit enough for you and your coding agents to follow a request from end to end. [Website](https://taphra.dev) | [Documentation](https://taphra.dev/docs/) | [Getting started](https://taphra.dev/docs/getting-started/) | [Changelog](https://taphra.dev/docs/changelog/) | [Security](SECURITY.md) ## Why Taphra - **One install.** `taphra/taphra` includes seven libraries (database, validator, container, crypt, localisation, AI, billing). Each of them also installs on its own, without the framework. - **AI in the same stack.** Anthropic, OpenAI (and OpenAI-compatible servers) and Ollama sit behind one interface with token streaming, structured output, conversations and an agent loop that calls your tools. The same app can expose tools, resources and prompts to MCP clients such as desktop AI apps, IDEs and coding agents. - **Safe defaults.** An unset or unknown `APP_ENV` runs the app in production mode, and the debug error page only exists in development. In the HTML starters, every request that is not GET, HEAD or OPTIONS must carry a CSRF token (the API starter uses bearer tokens instead, which need none). Values in conditions, `Criteria` and the query builder are bound as parameters; SQL you write as a string or through the `*Raw()` methods is yours to keep safe. `e()` and the form helpers escape what they print; helpers documented as taking HTML, such as `p()`, and `SafeString` print it as given. Session cookies are HttpOnly and SameSite=Lax. The MCP HTTP endpoint refuses every request until you give it a token or your own check. - **You can trace it.** A request goes from `app/Static/index.php` to the front controller, which asks the router for a controller and action, runs the PSR-15 middleware the route declares, and calls the method you wrote. That method returns a string or renders a plain PHP template. Configuration is YAML, one file per concern, with a section per environment. The framework is ordinary PHP classes that you can open and step through. ## Where Taphra comes from Taphra is new to the public, but it is not new. Its grandfather is WebAlgo, a minimal PHP framework that the people behind [Prodacity](https://prodacity.com) wrote and used from 2010 to 2020 to build several projects for their clients, which are still running today. It drew on that senior team's years of building tools on CakePHP, Django, Zend Framework, Symfony and other PHP and Python frameworks, and kept only what had held up on real projects. In all, they have used WebAlgo and Taphra on hundreds of projects. Much of Taphra started there: DataStores and their `Criteria` conditions, views, layouts and elements as plain PHP files, cache rules that clear entries when an event fires, widgets, queues and locks. `DataStore::find()` still takes the arguments it took in WebAlgo. Taphra 1.0 rebuilds that design for PHP 8.2, with PSR standards, Composer packages, a test suite that runs in CI and safe defaults, and adds AI providers, an agent loop and an MCP server. The agent era is its newest chapter, not its first. ## Built to be relied on - **Tested on every change.** About 2,000 tests on each of PHP 8.2, 8.3 and 8.4, a PostgreSQL suite against a real server, static analysis with PHPStan, end-to-end checks of the four starters (including CSRF, sign-in, token and rate-limit checks) and the five tutorials followed step by step. Bugs fixed before 1.0 have their own regression tests. See [CI](https://github.com/taphra/taphra/actions/workflows/ci.yml). - **Built on proven packages.** Symfony Console, YAML and Process, Doctrine Inflector, Whoops, Predis, Nyholm PSR-7 and PHPMailer, installed about 5.7 billion times between them on Packagist ([the list](https://taphra.dev/why/#foundations)). - **Semantic versioning.** No breaking changes within 1.x, fixes in patch releases, and security reports handled as described in [SECURITY.md](SECURITY.md). ## Requirements - PHP 8.2, 8.3 or 8.4 (CI tests all three) - Extensions: `curl`, `json`, `mbstring`, `pdo`, `sodium` - Composer - Optional: the PDO driver for your database (`pdo_mysql`, `pdo_pgsql`, `pdo_sqlite`), `intl` (CLDR plural rules and number formats), `pcntl` (several queue workers per process), `dom` (the HTML sanitiser), a Redis server for the Redis cache, session and queue drivers ## Install ```bash composer create-project taphra/skeleton my-app cd my-app php taphra serve ``` Open http://127.0.0.1:8000 for the welcome page and http://127.0.0.1:8000/health for a JSON endpoint. `php taphra serve` starts PHP's development server with `APP_ENV=dev`. Everywhere else the app runs in production mode until you set `APP_ENV=dev` (or `stg`). Three other starters use the same layout: | Starter | What it adds | |---|---| | `taphra/api-starter` | A JSON API with JWT login, a posts resource with ownership checks, CORS, rate limiting and RFC 7807 errors | | `taphra/ai-chat` | A streaming chat page (Server-Sent Events), conversation history, a prompt template and an example tool | | `taphra/mcp-server` | An MCP server over stdio and Streamable HTTP with example tools, a resource and a prompt | ```bash composer create-project taphra/mcp-server my-mcp-app ``` The framework itself is the `taphra/taphra` package (`composer require taphra/taphra`); the starters are the app structure around it. ## A short tour Routes map URLs to `controller/action`. Without a route, `/post/index` reaches `PostController::index()` by convention. ```yaml # app/Config/routes.yml GET: /posts: post/index /posts/{id:\d+}: post/show ``` A controller is a class in `app/Controllers`. Only the public methods you declare can be reached from a URL; the helpers the base class gives you (`redirect()`, `csrf()`, `sse()` and the others) cannot. ```php viewTitle = 'Posts'; $this->posts = PostDataStore::where('status', 'published') ->orderBy('id', 'desc') ->limit(20) ->get(); $this->autoRender = true; } // GET /posts/42: the {id} segment arrives as $id; an unknown id answers 404 public function show(int $id): void { $this->post = (new PostDataStore())->findOrFail(['id' => $id])->first(); $this->viewTitle = $this->post['title']; $this->autoRender = true; } } ``` Views are PHP templates. The properties you set on the controller become variables, and `e()` escapes a value for HTML. ```php

Posts

``` ```php

``` A DataStore is a class for one table. Static calls start a query; values in conditions and the query builder are sent to the database as bound parameters (SQL you write yourself goes through the `*Raw()` methods). ```php ```yaml # app/Config/ai.yml default_provider: anthropic providers: anthropic: api_key: "${ANTHROPIC_API_KEY}" model: claude-opus-5-5 ``` ```php use Taphra\Ai\AI; $reply = AI::complete([ ['role' => 'user', 'content' => 'Suggest a title for a post about PHP 8.4 property hooks.'], ]); echo $reply['content']; ``` `AI::stream()` yields the answer as it is generated, and `AI::agent()` runs a loop that lets the model call your tools. A controller can also serve MCP clients: the server lists each method marked `#[McpTool]` with its input schema and calls it with the client's arguments. It does not check the arguments against the schema, so treat them like form input. ```php 'object', 'properties' => ['word' => ['type' => 'string']], 'required' => ['word'], ], )] public function findPosts(array $params): array { return PostDataStore::where('status', 'published') ->whereContains(['title'], (string) $params['word']) ->pluck('title'); } } ``` `php taphra mcp:serve --list` prints what was found, and `php taphra mcp:serve` runs the server over stdio. In an MCP client's configuration: ```json { "mcpServers": { "my-app": { "command": "php", "args": ["/path/to/my-app/taphra", "mcp:serve"] } } } ``` The [guides](https://taphra.dev/docs/) cover each of these in depth, from [routing](https://taphra.dev/docs/routing/) and [DataStores](https://taphra.dev/docs/datastores/) to [AI](https://taphra.dev/docs/ai/) and [MCP](https://taphra.dev/docs/mcp/). ## Packages `taphra/taphra` includes these libraries. Each one is also published on its own and works without the framework. | Package | What it does | Standalone docs | |---|---|---| | `taphra/db` | DataStores, a query builder and a schema builder over PDO (SQLite, PostgreSQL, MySQL and MariaDB; SQL Server through generated SQL), plus a Redis connection and an experimental MongoDB connection | [packages/db](https://taphra.dev/docs/packages/db/) | | `taphra/validator` | Input validation with built-in and custom rules | [packages/validator](https://taphra.dev/docs/packages/validator/) | | `taphra/container` | A PSR-11 service container and service providers | [packages/container](https://taphra.dev/docs/packages/container/) | | `taphra/crypt` | Authenticated encryption with libsodium | [packages/crypt](https://taphra.dev/docs/packages/crypt/) | | `taphra/l10n` | Translations named by key or by source text, ICU MessageFormat (plural, select, number) | [packages/l10n](https://taphra.dev/docs/packages/l10n/) | | `taphra/ai` | AI providers, streaming, structured output, the agent loop, the MCP server | [packages/ai](https://taphra.dev/docs/packages/ai/) | | `taphra/billing` | One billing interface with a Stripe provider and a null provider for tests: customers, subscriptions, webhooks | [packages/billing](https://taphra.dev/docs/packages/billing/) | ```bash composer require taphra/db ``` ## Documentation Start with [Getting started](https://taphra.dev/docs/getting-started/), then follow the [guide index](https://taphra.dev/docs/): configuration, routing and controllers, views, requests and validation, the database, authentication and security, AI, MCP, queues, cache, events, the scheduler, email, localisation, billing, testing, the command line, deployment and upgrading. [How Taphra compares](https://taphra.dev/docs/framework-comparison/) with Laravel, Symfony and others is there too, with the cases where they are the better choice. ## Security Please report security problems privately, as described in [SECURITY.md](SECURITY.md). Do not open a public issue. ## Contributing Bug reports, fixes, docs and new features are welcome. [CONTRIBUTING.md](CONTRIBUTING.md) explains how to set up the repository and run the tests, and everyone taking part follows the [code of conduct](CODE_OF_CONDUCT.md). ## Licence Taphra is released under the [MIT License](LICENSE). Copyright 2019-2026 [Prodacity LLC](https://prodacity.com). --- Source: https://taphra.dev/docs/getting-started/ # Getting started This page takes you from an empty folder to a running Taphra app with one HTML page and one JSON endpoint. You need PHP and Composer; a database is optional until you add DataStores. ## Requirements - PHP 8.2, 8.3 or 8.4 (the test suite runs on all three). - The PHP extensions `curl`, `json`, `mbstring`, `pdo` and `sodium`. - Composer 2. - For a database: the PDO driver for it (`pdo_mysql`, `pdo_pgsql` or `pdo_sqlite`). Optional extensions: `intl` (full CLDR plural rules and number formats), `pcntl` (several queue workers and clean shutdown on SIGTERM), `dom` (the HTML sanitiser). ## Create an app ```bash composer create-project taphra/skeleton my-app cd my-app php taphra serve ``` `create-project` runs a post-install step that writes a random `APP_SECRET_KEY` to `.env` and creates the writable folders under `app/tmp/`. The skeleton's `composer.json` sets `config.platform.php` to `8.2.0`, so the lock file it writes also installs on PHP 8.2 ([Deployment](deployment.md#install-the-code) explains when to raise it). `php taphra serve` starts PHP's built-in server on http://127.0.0.1:8000 (change it with `--host` and `--port`). Open `/` for the welcome page and `/health` for a JSON response. An app runs in production mode unless the `APP_ENV` environment variable says otherwise: an unset or unknown value means production, with the plain error pages and no debug output. `php taphra serve` sets `APP_ENV=dev` for its server when the variable is not set, so you get the development error page while you work. [Configuration and environments](configuration.md) has the details. ## What the skeleton contains ```text my-app/ app/ bootstrap.php runs on every request; sets the mode from APP_ENV Config/ app.yml, databases.yml, routes.yml, migrations.yml Controllers/ AppController (base), HomeController, HealthController, AppErrorController DataStores/ AppDataStore (base class for your tables) Layouts/ default.lyt.php Migrations/ your migrations Models/ AppModel (base) Static/ the document root: index.php, .htaccess, frankenphp-worker.php Views/ home/index.tpl.php, error404.tpl.php, error500.tpl.php tmp/ file cache, logs, compiled config (must be writable) composer.json taphra the command line: php taphra list ``` Point your web server's document root at `app/Static/`. The `.htaccess` file there sends every request that is not a real file to `index.php` under Apache; `php taphra serve` does the same for the built-in server. Nothing connects to a database until you use a DataStore. Cache, sessions and logs use files under `app/tmp/`. ## A first page Generate a controller: ```bash php taphra make:controller Post ``` This writes `app/Controllers/PostController.php`. Give it an action: ```php viewTitle = 'Posts'; $this->posts = ['Hello, world', 'Second post']; $this->autoRender = true; } } ``` and a view for it: ```php

Posts

``` Open http://127.0.0.1:8000/post. With no route declared, the URL `/post` runs `PostController::index()`, and `/post/show/5` would run `show('5')`. Public properties you set on the controller become variables in the view, and `autoRender = true` renders `app/Views/post/index.tpl.php` inside the `default` layout. [Routing and controllers](routing.md) covers declared routes; [Views and helpers](views.md) covers templates and escaping. `PostController` extends the skeleton's `AppController`, which checks a CSRF token on every request that is not GET, HEAD or OPTIONS. Put `csrf() ?>` inside each form. ### Class files and autoloading The skeleton's `composer.json` maps the `App\` namespace to `app/` (PSR-4), so a class in a file named after it, such as `app/Controllers/PostController.php`, loads straight away. The `make:*` commands write files that way. The skeleton's own classes use the older `*.class.php` suffix (`HomeController.class.php`), which Composer finds through a classmap instead; if you add a `*.class.php` file by hand, run `composer dump-autoload` before the class can be found. ## A first JSON endpoint The skeleton's `HealthController` is a JSON endpoint: it extends `Taphra\RestController` and returns `$this->json()`. ```php json(['status' => 'ok', 'time' => gmdate('c')]); } } ``` `GET /status` now answers `{"status":"ok","time":"..."}` with `Content-Type: application/json`. `RestController` does not check CSRF tokens: protect endpoints that change data with token authentication ([Authentication](authentication.md)). [REST APIs](rest-apis.md) covers resources, errors and generated CRUD controllers. ## Other starters Three more Composer project templates start from a different place: | Package | What it contains | |---|---| | `taphra/api-starter` | A JSON API: JWT register and login endpoints, a posts resource with ownership checks, a PSR-15 pipeline (CORS, security headers, JSON body parsing, rate limiting) and migrations, on SQLite by default (MySQL or PostgreSQL by editing `app/Config/databases.yml`). | | `taphra/ai-chat` | A chat page that streams model replies over Server-Sent Events, with conversation history, a prompt template, an example tool and `app/Config/ai.yml`. The page is closed until you sign in with the `CHAT_PASSWORD` that `composer create-project` writes to `.env`, and messages are rate limited per visitor. | | `taphra/mcp-server` | An MCP server: a posts controller whose methods are MCP tools, resources and prompts, the stdio transport (`php taphra mcp:serve`) and the Streamable HTTP endpoint at `/mcp`. | ```bash composer create-project taphra/mcp-server my-server ``` ## Next steps - [Configuration and environments](configuration.md): the YAML files, modes and secrets. - [Routing and controllers](routing.md) and [Views and helpers](views.md). - [Requests and validation](requests.md). - [Database](database.md): connections, migrations and DataStores. - `php taphra list` shows every command ([CLI reference](cli.md)). --- Source: https://taphra.dev/docs/configuration/ # Configuration and environments Taphra reads its settings from YAML files in `app/Config/` and picks the environment (development, staging or production) from the `APP_ENV` environment variable. This page covers the files, the modes, secrets, the settings that matter on a public server, and how configuration is cached. ## The files | File | What it configures | Guide | |---|---|---| | `app.yml` | the app: name, default controller, cache, sessions, logging, URLs, proxies, mail | this page | | `routes.yml` | URL routes | [Routing](routing.md) | | `databases.yml` | database connections | [Database](database.md) | | `migrations.yml` | where migrations live and how their state is kept | [Database](database.md) | | `ai.yml` | AI providers and models | [AI](ai.md) | | `queue.yml` | queue connections | [Queues](queues.md) | | `cache.yml` | cache rules per controller action | [Cache](cache.md) | | `billing.yml` | payment providers | [Billing](billing.md) | A file that does not exist is not an error: every key in it returns its default. ## Environment sections Most files are split into sections. `all` applies everywhere; `dev`, `stg` and `prod` apply in one mode and override `all` key by key: ```yaml # app/Config/app.yml app_name: my-app all: default_controller: home default_action: index caching: method: file logging: method: file dev: display_errors: 1 prod: display_errors: 0 base_url: https://example.com trusted_proxies: [10.0.0.0/8] ``` `routes.yml` is the exception: its top-level sections are HTTP methods, and the router does not read `dev`, `stg` or `prod` there ([Routing](routing.md#declaring-routes)). ## Modes and APP_ENV The skeleton's `app/bootstrap.php` sets the mode on every request: ```php ```php use Taphra\Framework; echo Framework::modeFromEnvironment('local'), "\n"; // dev echo Framework::modeFromEnvironment('staging'), "\n"; // stg echo Framework::modeFromEnvironment(false), "\n"; // prod (APP_ENV not set) echo Framework::modeFromEnvironment('dev', '1'), "\n"; // prod (IS_PRODUCTION wins) if (Framework::mode() === Framework::DEVELOPMENT) { // or getMode() === TPHR_DEVELOPMENT echo "development mode\n"; } ``` `Framework::getInstance()` also gives the older service-locator style access (`getConfigManager('app')`, `getRouter()`, `getCache()`, `getContainer()`) that some framework code still uses; new code uses the classes directly or the [service container](container.md). What changes with the mode: - **Development** shows the Whoops debug page for uncaught errors, with the stack trace, request data and the queries the request ran. An HTTP exception keeps its status there (404 for a missing page, 403 for a failed CSRF check); other errors answer 500. - **Staging and production** answer with the right status and show the app's `Views/error404.tpl.php` (for a 404) or `Views/error500.tpl.php` (for any other error status) without details, and write the error to the log. - Production writes log entries from `notice` up; development writes everything ([Logging](logging.md)). - `url()` refuses to build a URL from the request's `Host` header in production (see below). ## Reading and setting values `Config::get()` takes a dot-notation key: the part before the first dot names the file, the rest is the path inside it, after the `all` and current-mode sections are merged. ```php use Taphra\Config; echo Config::get('app.app_name'), "\n"; // skeleton echo Config::get('app.caching.method'), "\n"; // file echo Config::get('app.mail.from', 'noreply@localhost'), "\n"; // the default: no such key $caching = Config::get('app.caching'); // ['method' => 'file'] $app = Config::get('app'); // the whole merged file Config::set('app.feature.beta', true); // in memory, for this request only var_dump(config('app.feature.beta')); // bool(true) ``` `Config::get()` returns an empty string for a missing key when you give no default; the `config($key, $default = null)` helper returns `null`. `Config::set()` changes the value in memory only (handy in tests and in `bootstrap.php`); it never writes the YAML file. ## Secrets and environment variables Keep secrets out of the YAML files you commit. Taphra reads environment variables with `getenv()`. - `composer create-project` and `php taphra key:generate` write a random 64-character `APP_SECRET_KEY` to `.env` (which the skeleton's `.gitignore` leaves out of Git). On a server, set that key and your other secrets in the server environment: a PHP-FPM pool (`env[APP_SECRET_KEY] = ...`), a systemd unit (`Environment=`), or a container (`docker run -e`, `environment:` in Compose). - `.env` holds one `NAME=value` per line; a value in double quotes may use `\n`, `\t`, `\"` and `\\` and may span lines, one in single quotes is taken as written. A quote that is never closed stops the boot with an error that names the line, instead of swallowing every line after it. - Read a secret where you need it, for example `Crypt::encrypt($data, getenv('APP_SECRET_KEY'))` ([Authentication and security](security.md)). - `ai.yml` and `billing.yml` replace `${NAME}` placeholders with environment variables, so `api_key: "${ANTHROPIC_API_KEY}"` keeps the key out of the file. Other files do not resolve placeholders. ## Base URL and proxies Two `app.yml` settings matter as soon as the app is on a public server: ```yaml # app/Config/app.yml prod: base_url: https://example.com trusted_proxies: [10.0.0.0/8, 127.0.0.1] ``` - **`base_url`** is what `url()` and `asset()` build absolute links from. Outside production, without it, `url()` falls back to the request's `Host` header. In production `url()` throws a `Taphra\Exceptions\ConfigurationException` when `base_url` is missing, because the `Host` header comes from the client and a forged one would end up in links such as password-reset emails. `asset()` uses `app.asset_url` (a CDN prefix, for example) when set. - **`trusted_proxies`** lists the addresses (single IPs or CIDR ranges, IPv4 or IPv6) of your load balancer or reverse proxy. Only when a request comes from one of them does Taphra read `X-Forwarded-For` for the client IP (`Request::clientIP()`, used by rate limiting and logs) and `X-Forwarded-Proto` to tell that the request was HTTPS (secure cookies, HSTS). Without it these headers are ignored, so a client cannot fake its address. ```php use Taphra\Config; Config::set('app.base_url', 'https://example.com'); echo url('/posts/42'), "\n"; // https://example.com/posts/42 echo url(), "\n"; // https://example.com echo asset('css/app.css'), "\n"; // https://example.com/css/app.css ``` ## Drivers Cache, sessions, logs and locks use files under `app/tmp/` until you choose another driver in `app.yml`: | Setting | Values | Default | |---|---|---| | `caching.method` | `file`, `redis`, `memcache`, `apc` (APCu); servers in `caching.servers` | `file` | | `session.method` | `file`, `database` | `file` | | `logging.method` | `file`, `syslog`, `null` (discard) | `file` | | `logging.level` | `debug`, `message`, `notice`, `warning`, `error` | `notice` in production, everything in development | | `lock.method` | `file`, `database` | `file` | The [Cache](cache.md), [Logging](logging.md) and [Authentication](authentication.md) guides cover each one; session cookie settings (`session.cookie`) are in [Authentication and security](security.md). `app/tmp/` must be writable by the web server user. ## How configuration is cached Parsing YAML on every request would be slow, so each file is compiled to a PHP array under `app/tmp/config_cache/`, which OPcache keeps in memory. - A changed YAML file is picked up on the next request, in every mode: each cached copy (in `app/tmp/config_cache/` and, in staging and production, in the app cache) records the file's modification time and size and is used only while the file still has them. - `php taphra cache:clear` and `php taphra optimize:clear` delete both copies. - `php taphra optimize` compiles configuration and routes into one file loaded at boot; run it on every deploy and `php taphra optimize:clear` to undo it ([Deployment](deployment.md)). --- Source: https://taphra.dev/docs/routing/ # Routing and controllers This page covers how a URL reaches a controller action: the `/controller/action` convention, routes declared in `app/Config/routes.yml`, named routes, route groups with middleware, and what a controller action can do. It assumes the skeleton app from [Getting started](getting-started.md). ## Contents - [How a URL reaches an action](#how-a-url-reaches-an-action) - [Declaring routes](#declaring-routes) - [HTTP methods and 405](#http-methods-and-405) - [Named routes and URL generation](#named-routes-and-url-generation) - [Adding routes from PHP](#adding-routes-from-php) - [Routes from a package](#routes-from-a-package) - [Route groups and middleware](#route-groups-and-middleware) - [A middleware pipeline for every request](#a-middleware-pipeline-for-every-request) - [Controllers](#controllers) - [Server-Sent Events](#server-sent-events) - [HTMX](#htmx) ## How a URL reaches an action When no declared route matches, the path itself names the action: | URL | Runs | |---|---| | `/` | `app.default_controller` and `app.default_action` from `app.yml` (`HomeController::index()` in the skeleton) | | `/post` | `PostController::index()` (the default action) | | `/post/show` | `PostController::show()` | | `/post/show/5/draft` | `PostController::show('5', 'draft')` | The first segment, with its first letter upper-cased, plus `Controller` gives the class in `App\Controllers`. For a multi-word controller use the class's own casing in URLs and route targets (`blogPost/index` for `BlogPostController`): class files are found by exact name. A declared route can also name a controller by its full class name, such as a package's controller (see [Routes from a package](#routes-from-a-package)). The convention never does: a request path cannot hold a backslash. A route that names one of your own controllers in full (`App\Controllers\PostController/destroy`) binds the action as the short form (`post/destroy`) does, so its method and middleware also guard the convention URL (below). Only public methods that your own controller classes declare are actions. The helpers and hooks of the base classes are not reachable from a URL, even when a subclass overrides them: `/post/redirect`, `/post/csrf`, `/post/sse`, `/post/json` and `/post/beforeAction` all answer 404, and so does `/appError/onError` on an error controller (a subclass of `Taphra\ErrorController`). Static methods, methods whose name starts with `_`, and methods carrying an MCP attribute (`#[McpTool]` and the others, see [MCP server](mcp.md)) are not actions either. ## Declaring routes Declared routes give you clean URLs, HTTP methods and parameters. They live in `app/Config/routes.yml`: ```yaml # app/Config/routes.yml GET: /posts: post/index /posts/{id:\d+}: post/show /tags/:slug: post/tag /archive/(\d+)/(\d+): post/archive/%2/%1 POST: /posts: post/store /posts/{id:\d+}/delete: post/destroy all: /about: post/about names: post.show: /posts/{id:\d+} tag.show: /tags/:slug groups: admin: prefix: /admin middleware: [App\Middleware\RequireToken] routes: GET /dashboard: admin/stats ``` The top-level sections are: - `GET`, `POST`, `PUT`, `PATCH`, `DELETE`, `OPTIONS`, `HEAD`: routes for that method only. - `all`: routes for any method. A method section wins over `all` for the same path. - `names`: names for URL generation (see below). - `groups`: routes that share a prefix and middleware (see below). The router reads only these sections. The `dev:`, `stg:` and `prod:` sections in the skeleton's `routes.yml` are not read for routing, so routes cannot differ per environment. Each entry maps a path to a `controller/action` target. A path can hold parameters: | Form | Matches | Example | |---|---|---| | `{name}` | one path segment | `/users/{id}` | | `{name:regex}` | the regular expression | `/posts/{id:\d+}` | | `:name` | one path segment, at the start of a segment | `/tags/:slug` | | `(regex)` with `%1`, `%2` in the target | positional captures, in any order | `/archive/(\d+)/(\d+): post/archive/%2/%1` | Named parameters are passed to the action in order. A parameter typed `int` receives an integer. Braces in a path always start a parameter, so a quantifier such as `\d{4}` cannot be used in a route: write `\d+`. ```php getRoutes()` returns the same list, one entry per route with its `method` (`ALL` for the `all:` section), `pattern` and `target`. The pattern is the regular expression the router matches, not the path as written: every slash is escaped and a named parameter is replaced by its expression, so `/posts/{id:\d+}` is `\/posts\/(\d+)` and `/tags/{slug}` is `\/tags\/([^\/]+)`. `str_replace('\/', '/', $route['pattern'])` gives the form `route:list` prints (`/tags/([^/]+)`). A target without `%1`, `%2`... placeholders gets one for each named parameter, so `post/show` becomes `post/show/%1`. ## HTTP methods and 405 - A request whose path matches a declared route for other methods only gets `405 Method Not Allowed` with an `Allow` header: `DELETE /posts` answers 405 with `Allow: GET, POST`. - `HEAD` is answered like `GET` when no `HEAD` routes are declared. - A convention URL cannot run an action that declared routes bind to some methods only: `GET /post/destroy/7` answers 405 with `Allow: POST`, so a link or an `` tag cannot trigger it. - A convention URL cannot reach an action that a route binds with middleware: `AdminController::stats()` runs only through `/admin/dashboard`, which needs the token (401 without it), and the convention URL `/admin/stats` answers 404. Every request that is not GET, HEAD or OPTIONS to a controller that extends the skeleton's `AppController` must carry the CSRF token, so `POST /posts` without one answers 403. See [Views and helpers](views.md#forms-and-csrf). ## Named routes and URL generation Names come from the `names:` section (or from `addRoute()`, below). `Router::route()` builds the path; pass parameters by name or by position: ```php use Taphra\Router; $router = Router::getInstance(); echo $router->route('post.show', ['id' => 42]), "\n"; // /posts/42 echo $router->route('post.show', [42]), "\n"; // /posts/42 echo $router->route('tag.show', ['slug' => 'php']), "\n"; // /tags/php ``` `route()` throws a `Taphra\TaphraException` for an unknown name, an unknown parameter name or a missing parameter. For an absolute URL, pass the path to `url()`: `url($router->route('post.show', ['id' => 42]))`. In production `url()` needs `base_url` in `app.yml` (see [Configuration](configuration.md#base-url-and-proxies)). ## Adding routes from PHP `addRoute()` and `addRouteGroup()` register routes at run time, for example in `app/bootstrap.php`: ```php addRoute('GET', '/feed/{format:rss|atom}', 'post/feed', 'feed'); // addRouteGroup(prefix, routes, middleware) $router->addRouteGroup('/api/v1', [ 'GET /stats' => 'admin/stats', ], [App\Middleware\RequireToken::class]); ``` The method can be `'ALL'`. The group's routes can also be given per method: `['GET' => ['/stats' => 'admin/stats']]`. ## Routes from a package A Composer package (a module of your app, or a library) can ship its own controllers and routes. The controllers live in the package's namespace, and the package's service provider registers the routes with `addPackageRoutes(namespace, routes, middleware)`: ```php addPackageRoutes('Acme\Blog\Controllers', [ 'GET /blog' => 'post/index', // Acme\Blog\Controllers\PostController::index() 'GET /blog/{id:\d+}' => 'post/show', 'POST /blog' => 'post/store', 'names' => ['blog.show' => '/blog/{id:\d+}'], ]); } } ``` ```php target`, or `'GET' => ['/path' => target]`, with `ALL` for any method), and a `names` entry names paths for `route()`. The third argument is a list of middleware that runs before each of these routes, on both entries. - **The app keeps priority,** whatever order the routes were added in. A path that a route of the app (`routes.yml`, `addRoute()`, `addRouteGroup()`) declares is the app's for every method: a package route never answers it, and a method the app does not serve there gets the app's 405, `HEAD` included. Your controllers are reached only by your own routes and convention URLs, with their guards (middleware, methods, themed variants), exactly as without packages. The home page stays the app's `default_controller`, and a route name the app uses keeps the app's path. When two packages declare the same method and path, the first one registered wins; a `HEAD` request gets a package's `GET` route when no package declares `HEAD` for the path. Like every declared route, a package route comes before the `/controller/action` convention, so a package keeps its paths under a prefix of its own (`/blog`). - **The same checks.** A package controller extends `Taphra\Controller` (or `RestController`), and only the methods its own class declares are actions, as for the app's controllers. The convention URL cannot reach a package controller: only its routes can. - **`php taphra route:list`** lists the package routes after the app's, with the controller's full class name, and marks each package route whose path an app route declares: `(the app's route is used)` when an app route answers that method, `(the app answers this path with 405)` when the app declares the path for other methods only, and, for a package `ALL` route, `(the app answers this path: its route or 405)`. Paths are compared as written: an app route whose pattern differs but also matches is not marked. - **Route caching and worker mode.** `php taphra optimize` freezes the app's routes only. The provider adds the package's routes again when the providers boot, once per process: on every request with PHP-FPM, once per worker in FrankenPHP worker mode. `render()` looks for views in the app's `app/Views/`. A package controller returns its output, or renders a template of its own inside the app's layout: `$this->fileDirectRender(__DIR__ . '/../../views/post/show.tpl.php');` in an action that returns nothing (pass `false` as the second argument to leave the layout out). The app can mount a package controller at a path of its own: a target in `routes.yml` may name a controller by its full class name too, and the app's route comes first. ```yaml # app/Config/routes.yml GET: /news/{id:\d+}: Acme\Blog\Controllers\PostController/show ``` ## Route groups and middleware A group gives its routes a common prefix and a list of PSR-15 middleware class names. The middleware runs before the action on both entries the app can use (the default `index.php`, and a PSR-15 pipeline, below). A middleware that returns its own response (a 401, a 429) stops the request there. A route path in a group is added to the prefix, and a trailing slash is dropped, because request paths never end with one. So `GET /` in the `admin` group above is the group's own page, `/admin`, and `GET /reports/` answers `/admin/reports`. ```php getHeaderLine('X-Token'))) { return new Response(401, ['Content-Type' => 'text/plain'], 'Missing or wrong token'); } return $handler->handle($request); } } ``` ```php pipe(new SecurityHeadersMiddleware()) ->pipe(new RequestBodyMiddleware()) ->pipe(new ActionDispatcherMiddleware()) ->handle(ServerRequestFactory::fromGlobals()); http_response_code($response->getStatusCode()); foreach ($response->getHeaders() as $name => $values) { header($name . ': ' . implode(', ', $values)); } echo $response->getBody(); ``` The built-in middleware lives in `Taphra\Http`: `SecurityHeadersMiddleware`, `RequestBodyMiddleware` (JSON and form bodies), `JsonBodyMiddleware`, `CorsMiddleware`, `RateLimitMiddleware`, `RequestIdMiddleware`, `AuthMiddleware`, `ContentNegotiationMiddleware`, `LocaleMiddleware` and `RequestLogMiddleware`. [Authentication and security](security.md) covers the security-related ones. On this entry a 404 has an empty body instead of the app's error page. ## Controllers HTML controllers extend the skeleton's `AppController` (which extends `Taphra\Controller` and turns on the CSRF check). JSON controllers extend `Taphra\RestController` ([REST APIs](rest-apis.md)). What an action returns decides the response: - A string (or any non-null value) is the response body. - `null` with `$this->autoRender = true` renders `app/Views//.tpl.php` in the layout; public properties you set on the controller are the view's variables ([Views and helpers](views.md)). - `RestController::json($data, $status = 200)` returns a JSON body and sets the status and `Content-Type`. ```php layout = 'default'; } public function show(int $id): string { if ($id !== 1) { throw new NotFoundException('No such account'); } return 'Account 1'; } public function legacy(): void { $this->redirect('/account/show/1'); } public function save(): string { // ... store the form ... $this->header('Cache-Control', 'no-store'); return $this->seeOther('/account/show/1'); // 303, Location: /account/show/1 } public function export(): string { throw new HttpException(429, 'Try again in a minute'); } } ``` - `beforeAction()` runs before every action. The base hook runs the CSRF check, so an override calls `parent::beforeAction()` first. `afterAction(string &$content)`, `beforeRender()` and `afterRender(string &$content)` are the other hooks. - `redirect($url)` sends a `Location` header and ends the request: it ends the PHP process, so nothing after it runs. `return $this->seeOther($url);` answers with a 303 See Other and the `Location` header and returns from the action instead, so the request ends normally (`afterAction()` and the PSR-15 middleware run) and an in-process test sees the redirect ([Testing](testing.md#html-pages-redirects-and-htmx)). For both, pass a path or URL you built, never one taken from the request, or the redirect can send users to another site. - `$this->header($name, $value)` sets a response header on both entries, the same way `RestController`'s does: PHP's `header()` for the web server, and the PSR-7 response of the PSR-15 pipeline (which `HttpTestCase` reads). A header set with PHP's `header()` alone does not reach that response from the command line. - Throw `Taphra\Exceptions\NotFoundException` (404), `ForbiddenException` (403), `UnauthorizedException` (401) or `HttpException($status, $message)` to answer with that status. In production the body is the app's `Views/error404.tpl.php` for a 404 and `Views/error500.tpl.php` for every other status (the skeleton's says "500", so give it neutral wording if you use other codes); in development the debug page keeps that status. - A parameter typed as a `FormRequest` subclass is built from the request, and its `authorize()` runs before the action. Validation runs when the action calls `fails()`, `errors()` or `validated()`; `validated()` refuses invalid input with a 422 ([Requests and validation](requests.md)). ## Server-Sent Events `sse()` streams a Generator (or a Closure that returns one) as `text/event-stream`. Each yielded string becomes one `data:` event (a multi-line string becomes several `data:` lines), a final `data: [DONE]` event closes the stream, and the request ends: ```php // in a controller public function progress(): void { $this->sse(function () { foreach (['Parsing', 'Indexing', 'Done'] as $step) { yield $step; sleep(1); } }); } ``` `sse()` turns off output buffering and sends `X-Accel-Buffering: no` for nginx. It stops when the client disconnects. A PHP-FPM worker is busy for as long as a stream stays open. [AI](ai.md) shows how to stream a model's reply this way. ## HTMX `isHtmx()` is true when the request carries `HX-Request: true`. `renderPartial($view, $vars = [])` renders a view without the layout, which is what an HTMX swap expects: ```php // in a controller public function index(): void { $this->posts = ['Hello, world', 'Second post']; if ($this->isHtmx()) { $this->renderPartial('_list'); // app/Views/post/_list.tpl.php return; } $this->autoRender = true; } ``` The other helpers read the HTMX request headers (`htmxTarget()`, `htmxTrigger()`, `htmxTriggerName()`, `htmxCurrentUrl()`) or set response headers: `htmxPushUrl($url)`, `htmxReswap($strategy)`, `htmxRetarget($selector)` and `htmxTriggerEvent($event)` return the controller so they chain, and set their header the way `header()` does, so tests see it too; `htmxRedirect($url)` and `htmxRefresh()` end the request. To redirect an HTMX request and return from the action, set the header yourself: `$this->header('HX-Redirect', '/inbox'); return '';`. --- Source: https://taphra.dev/docs/views/ # Views and helpers Views are plain PHP templates. This page covers views, layouts, elements and blocks, how output is escaped, the global template helpers, the HTML and form helper, CSRF fields, widgets and Vite assets. It assumes you know how an action renders ([Routing and controllers](routing.md#controllers)). ## Contents - [Views](#views) - [Escaping](#escaping) - [Layouts](#layouts) - [Elements and blocks](#elements-and-blocks) - [Template helpers](#template-helpers) - [The HTML helper](#the-html-helper) - [Forms and CSRF](#forms-and-csrf) - [Widgets](#widgets) - [Vite](#vite) ## Views A view is `app/Views//.tpl.php`. An action that sets `$this->autoRender = true` and returns nothing renders its view inside the controller's layout. The controller's public properties become the view's variables: ```php viewTitle = 'Fish & Chips'; $this->title = 'Fish & Chips <3'; $this->article = ['body' => 'not bold', 'tags' => ['food', 'uk']]; $this->notice = new SafeString('Trusted markup'); $this->autoRender = true; } } ``` ```php

element('tag-list', ['tags' => $article['tags']]) ?> anchor(['href' => '/articles?q=' . rawurlencode('a&b'), 'text' => 'Search "a&b"']) ?> ``` To render something else, call `render()` from the action: ```php // in a controller action $this->render(); // the action's view in $this->layout $this->render('list'); // app/Views//list.tpl.php $this->render('list', 'minimal'); // with app/Layouts/minimal.lyt.php $html = $this->render('list', null, false); // return the HTML instead of printing it $this->renderPartial('_row', ['row' => $row]); // no layout (for HTMX and fragments) ``` A view name in camelCase also finds a snake_case file: the action `showLogin` renders `show_login.tpl.php` when `showLogin.tpl.php` does not exist. ## Escaping Inside a view the rules are: - Every top-level string variable is HTML-escaped once before the template runs, so `` prints `Fish & Chips <3`. - `e()` escapes a value for HTML. It recognises a variable the view already escaped and does not escape it again, so `` prints the same thing. Use `e()` everywhere: then you never have to remember which values were escaped. - Strings inside arrays and objects (`$article['body']`, `$row->name`) are not escaped for you: print them with `e()`. - A `Taphra\SafeString` is printed as it is. Use it only for markup you built or cleaned yourself; clean user-supplied rich text with `Taphra\HtmlSanitizer::clean($html)` first (it needs `ext-dom`). - Escaping is for HTML text and quoted attribute values. For JavaScript use `json_encode()`, for a URL component `rawurlencode()`. Do not call `htmlspecialchars()` on a view variable: it escapes the already-escaped value a second time (`&amp;`). `e()` does not. ## Layouts A layout wraps the view. It is `app/Layouts/.lyt.php`, chosen by the controller's `$layout` property (`default` in the skeleton). Inside it, `$this` is the view object and holds: | Property | Content | |---|---| | `$this->viewContent` | the rendered view | | `$this->viewTitle` | the controller's `$viewTitle` (not escaped) | | `$this->viewStyleSheets`, `$this->viewScripts` | tags added with `$this->addCss()` and `$this->addJS()` in the view | | `$this->viewLang`, `$this->viewCharSet`, `$this->viewDocType` | page settings (`en-US`, `UTF-8`, HTML5 by default) | | `$this->viewVars` | the controller's properties, not escaped | ```php <?= e($this->viewTitle) ?> viewStyleSheets ?>
viewContent ?>
viewScripts ?> ``` Layout values are not escaped for you, so the title goes through `e()`. ## Elements and blocks An element is a reusable fragment in `app/Elements/.elm.php`. From a view, `$this->element('name', $params)` prints it (pass `true` as the fourth argument to get the HTML back instead). The parameters become its variables, escaped like a view's; the controller's properties are in `$actionvars`. A view variable passed on to an element is already escaped, and the element does not escape it again: with `$this->element('card', ['name' => $name])`, `` and `` in the element print `O'Brien & Co` for `O'Brien & Co`, once. The same holds for an element that passes it on to another element. Pass any other string as it is, not through `e()` or `htmlspecialchars()` (the element escapes it); a `SafeString` stays as it is, and arrays and objects are passed unchanged, so print the strings inside them with `e()`. ```php
``` A controller renders an element directly with `$this->renderElement('tag-list', ['tags' => $tags])`. Blocks let a view hand content to the layout. The view captures it, the layout prints it: ```php startBlock('head') ?> endBlock('head') ?> blocks['head'])) $this->block('head'); ?> ``` ## Template helpers These global functions work in views and anywhere else: | Function | Returns | |---|---| | `e($value)` | the value escaped for HTML (once; a `SafeString` as is; arrays and objects as JSON) | | `old($field, $default = '')` | the field's value from the last failed form submission, escaped, else `$default` escaped | | `error($field, $wrap = '%s')` | the field's first validation error, placed in `$wrap`, or `''` | | `url($path = '')` | an absolute URL from `app.base_url` ([Configuration](configuration.md#base-url-and-proxies)) | | `asset($path)` | an absolute URL under `app.asset_url`, else under `url()` | | `classes($map)` | a class list: `classes(['btn', 'active' => $isActive])` | | `when($condition, $value, $else = '')` | `$value` or `$else` as a string | | `config($key, $default = null)` | `Config::get()` | | `__($key, $replace = [])` | a translation ([Localisation](localisation.md)) | | `dump(...)`, `dd(...)`, `pr($value)`, `vd(...)` | debug output (`dd()` stops the request) | ```php echo e('Tom & "Jerry"'), "\n"; // Tom & "Jerry" echo classes(['btn', 'btn-primary' => true, 'disabled' => false]), "\n"; // btn btn-primary echo when(false, 'checked', 'unchecked'), "\n"; // unchecked echo e(new \Taphra\SafeString('ok')), "\n"; // ok ``` Each global is defined only when no function of that name exists yet, so your app (or a library such as `symfony/var-dumper`, which has its own `dump()` and `dd()`) can define its own. `Taphra\Helpers` has the same helpers as static methods (`Helpers::e()`, `Helpers::old()`, `Helpers::error()`, `Helpers::url()`, `Helpers::asset()`, `Helpers::classes()`, `Helpers::when()`, `Helpers::dump()`, `Helpers::dd()`, `Helpers::pr()`, `Helpers::vd()`); the framework calls those, and so can code that must get Taphra's behaviour whatever the globals are. ```php use Taphra\Helpers; echo Helpers::e(' // ``` In a layout, `` goes in the ``; with `@vitejs/plugin-react`, put `` before it. `ViteHelper::asset('src/images/logo.png')` gives one file's URL. Outside development the helper reads `manifest.json` (Vite 5 writes it to `.vite/manifest.json`) from `build_dir`, or by default from `public/dist` next to `app/` or `app/Static/dist`. --- Source: https://taphra.dev/docs/requests/ # Requests and validation This page covers reading request input with `Taphra\Request`, JSON bodies, uploaded files, the validator, and the two ways to validate in a controller: `$this->validate()` and form request classes. The full rule reference is in the [validator package README](../packages/validator/README.md). ## Reading input `Taphra\Request` has static accessors over the current request. Nothing is sanitised on the way in: escape at the point of use (`e()` in HTML, bound values in SQL, `json_encode()` in JSON). The examples on this page use these routes: ```yaml # app/Config/routes.yml GET: /search: search/index POST: /api/posts: apiPost/store ``` ```php json([ 'q' => Request::str('q'), // trimmed string, '' when absent 'page' => Request::int('page', 1), // cast to int, 1 when absent 'exact' => Request::bool('exact'), // '1', 'true', 'on', 'yes' are true 'tags' => Request::array('tags'), // an array, a scalar wrapped in one 'filters' => Request::only(['lang', 'year']), // exactly these keys, null when absent ]); } } ``` `GET /search?q=+php+&page=2&tags[]=web&lang=en` answers `{"q":"php","page":2,"exact":false,"tags":["web"],"filters":{"lang":"en","year":null}}`. | Method | Returns | |---|---| | `Request::input($name, $default = null)` | the raw value from the form body or the query string (the body wins) | | `Request::str()`, `int()`, `float()`, `bool()`, `array()` | the value cast to that type, or the default | | `Request::only(array $keys)`, `except(array $keys)` | a whitelisted or filtered array of input | | `Request::fromGet($name)`, `fromPost($name)` | a value from one source only | | `Request::from('get')`, `from('post')`, `from('input')` | the same typed accessors bound to one source: `Request::from('get')->int('page', 1)` | | `Request::GET()`, `Request::POST()` | the whole query string or form body as an array | | `Request::requestMethod()` | `GET`, `POST` and so on, upper case | | `Request::headers()` | request headers, keys like `ACCEPT-LANGUAGE` | | `Request::server($key, $default = null)` | a `$_SERVER` value | | `Request::uri()`, `referer()`, `userAgent()`, `isAjax()` | the path and query string, the `Referer` header, the `User-Agent` header, whether `X-Requested-With: XMLHttpRequest` was sent | | `Request::clientIP()` | the client address (see below) | Use `only()` (or a validator's validated fields) when you pass input to a DataStore, so a client cannot add columns you did not expect. DataStores also respect `$fillable` and `$guarded` ([DataStores](datastores.md#input-safety)). ### The client IP `Request::clientIP()` returns `REMOTE_ADDR`, the address the connection came from. Headers a client can set, such as `X-Forwarded-For`, count only when the connection comes from an address listed in `app.trusted_proxies`; the client is then the last address in `X-Forwarded-For` that is not itself a trusted proxy. Set `trusted_proxies` when the app runs behind a load balancer ([Configuration](configuration.md#base-url-and-proxies)), or every client gets the balancer's address. ## JSON bodies PHP fills `$_POST` only for form submissions. With the skeleton's default `index.php`, a JSON request body is not in `Request::input()`; read it through a [form request](#form-requests) (which merges the JSON body into its input) or decode it yourself: ```php // in a controller action $data = json_decode(\Taphra\Request::rawBody(), true) ?? []; ``` With a PSR-15 pipeline in `index.php` ([Routing](routing.md#a-middleware-pipeline-for-every-request)), `RequestBodyMiddleware` parses JSON and form bodies and the dispatcher copies the result into `$_POST`, so `Request::input()` sees JSON fields too. ### The raw body `Request::rawBody()` returns the body as the client sent it, byte for byte: what a webhook's signature is computed over, an XML document, a JSON text before decoding. On the PSR-15 entry it is the body of the PSR-7 request being dispatched, in route middleware (a signature check, say) as in the action, so an in-process test can send it ([Testing](testing.md#raw-bodies-webhooks-and-xml)); on the default entry it is `php://input`. ```php // in a RestController action receiving a signed webhook $payload = \Taphra\Request::rawBody(); $expected = hash_hmac('sha256', $payload, (string) getenv('WEBHOOK_SECRET')); if (!hash_equals($expected, (string) \Taphra\Request::server('HTTP_X_SIGNATURE', ''))) { return $this->apiError(401, 'Bad signature'); } $event = json_decode($payload, true); if (!is_array($event)) { return $this->apiError(400, 'The body is not JSON'); } return $this->json(['received' => $event['event'] ?? null]); ``` ## Uploaded files Uploads arrive in PHP's `$_FILES`. Taphra adds no upload wrapper, so check the error code, the size and the real content type before you keep a file, and store it under a name you generate, outside `app/Static/`: ```php // in a controller action handling $file = $_FILES['avatar'] ?? null; if (!$file || $file['error'] !== UPLOAD_ERR_OK || $file['size'] > 2_000_000) { throw new \Taphra\Exceptions\HttpException(422, 'Send an image of at most 2 MB.'); } $type = (new \finfo(FILEINFO_MIME_TYPE))->file($file['tmp_name']); $ext = ['image/png' => 'png', 'image/jpeg' => 'jpg'][$type] ?? null; if ($ext === null) { throw new \Taphra\Exceptions\HttpException(422, 'Only PNG and JPEG images.'); } move_uploaded_file($file['tmp_name'], APP_PATH . '/uploads/' . bin2hex(random_bytes(16)) . '.' . $ext); ``` The form needs `enctype="multipart/form-data"`; `$html->file('avatar')` prints the input ([Views and helpers](views.md#the-html-helper)). ## The validator `Taphra\Validator` checks an array against rules written as pipe strings or arrays: ```php use Taphra\Validator; $v = Validator::make( ['email' => 'alice@example', 'age' => '17', 'password' => 'hunter2', 'site' => 'javascript:alert(1)'], [ 'email' => 'required|email', 'age' => 'required|integer|min:18', 'password' => 'required|string|min:8', 'site' => 'nullable|url', 'role' => ['required', 'in:admin,editor'], ] )->validate(); var_dump($v->fails()); // bool(true) echo $v->firstError('age'), "\n"; // The age must be at least 18. echo implode(', ', array_keys($v->errors())), "\n"; // email, age, password, site, role ``` The built-in rules: | Rule | Passes when the value | |---|---| | `required` | is present and not `null`, `''` or `[]` | | `nullable` | is anything; when it is `null` or `''` the other rules are skipped | | `sometimes` | is anything; when the field is absent the other rules are skipped | | `email`, `url`, `domain`, `phone`, `json`, `date` | is an email address, a URL, a domain name, a phone number (7 to 15 digits, or `phone:min,max`), valid JSON, a date `strtotime()` reads | | `string` | is text: a JSON number, boolean, list or object is not | | `integer`, `numeric`, `boolean` | is an integer, a number, or one of `true`, `false`, `0`, `1`, `"0"`, `"1"`, `"true"`, `"false"` | | `alpha`, `alpha_num` | has ASCII letters only, or letters and digits only | | `min:n`, `max:n` | has at least or at most `n` (see below) | | `min_digits:n`, `max_digits:n` | has at least or at most `n` digit characters | | `in:a,b,c`, `not_in:a,b,c` | is one of the listed values, or none of them | | `confirmed`, `confirmed:other` | equals the field `_confirmation`, or the named field | | `regex:/pattern/` | matches the pattern (use the array form when the pattern contains `\|`) | | `starts_with:x`, `ends_with:x` | starts or ends with the text | | `unique:connection,table,column` | is not already in that column (add `,except_column,except_value` to ignore the row being edited) | Rules other than `required`, `nullable` and `sometimes` are skipped for an empty value. A few behaviours to know: - **`min` and `max` measure strings by length.** A number is compared by value; a numeric string is compared by value only when the field also has `integer` or `numeric` (`integer|min:18` rejects `"17"`); any other string is compared by its length in characters (`min:8` rejects `"99"`); an array by its number of elements. A JSON body can send a number or a list where you expect text, so add `string` to text fields such as passwords: `string|min:8` rejects `99` and `[1,2,3,4,5,6,7,8]`. - **`url` accepts `http`, `https` and `ftp` only.** `javascript:`, `data:` and `file:` URLs fail. List schemes to change that: `url:https` or `url:http,https,mailto`. - **An unknown rule throws.** A rule name that is neither built in nor registered with `Validator::extend()` throws an `InvalidArgumentException` naming the rule and the field, even when the field is empty, so a typo such as `emial` fails loudly instead of letting every value through. - An array value fails rules that expect a single value (`email`, `in`, `regex` and the others). Add your own rules with `Validator::extend()`: ```php use Taphra\Validator; Validator::extend( 'even', fn (string $field, mixed $value, array $params, array $data): bool => is_numeric($value) && (int) $value % 2 === 0, ':field must be an even number' ); $v = Validator::make(['seats' => '7'], ['seats' => 'required|even'])->validate(); echo $v->firstError('seats'), "\n"; // seats must be an even number ``` ### Field names in messages Messages name a field by its input name. `attributes()` gives fields a readable name, used by every message, the built-in ones and the `:field` of your own rules alike. `errors()` stays keyed by the input name: ```php use Taphra\Validator; $v = Validator::make( ['rate_limit_per_minute' => '0'], ['rate_limit_per_minute' => 'required|integer|min:1', 'webhook_url' => 'required|url'] )->attributes(['rate_limit_per_minute' => 'rate limit', 'webhook_url' => 'webhook address']); echo $v->firstError('rate_limit_per_minute'), "\n"; // The rate limit must be at least 1. echo $v->firstError('webhook_url'), "\n"; // The webhook address field is required. echo implode(', ', array_keys($v->errors())), "\n"; // rate_limit_per_minute, webhook_url ``` A field without a name keeps its input name, so validators that do not call `attributes()` give the same messages as before. A form request names its fields in an `attributes()` method (below). `$this->validate()` in a controller uses the input names. ## Validating in a controller `$this->validate($data, $rules)` validates and returns only the fields that have rules. When validation fails it ends the request itself: - for a JSON request (`Accept` or `Content-Type` naming `application/json`): status 422 with a problem-details body, `{"type":"about:blank","title":"Unprocessable Entity","status":422,"detail":"The given data was invalid.","errors":{...}}`; - otherwise: it stores the errors and the submitted input in the session (`_tphr_errors` and `_tphr_old`) and redirects back to the `Referer` (or `/`). ```php // app/Controllers/PostController.php (actions) public function create(): void { $this->errors(); // read the errors flashed by a failed store() $this->autoRender = true; // the form uses old() and error() } public function store(): void { $data = $this->validate(\Taphra\Request::POST(), [ 'title' => 'required|max:200', 'body' => 'required', ]); // $data has only title and body $this->redirect('/posts'); } ``` In the form view, `old('title')` refills the field and `error('title', '

%s

')` shows the message ([Forms and CSRF](views.md#forms-and-csrf)). To report an error the validator cannot see (a duplicate found by a query, say), call `$this->withErrors(['title' => ['That title is taken.']], $data)` and render the form again. ## Form requests A form request is a class that holds the rules (and an authorisation check) for one action. Type-hint it on the action and the framework builds it from the query string, the form body and a JSON body, then calls `authorize()` before the action runs: ```php 'required|max:200', 'status' => 'required|in:draft,published', ]; } public function authorize(): bool { return true; // for example: \Taphra\Auth\Auth::check() } public function attributes(): array { return ['status' => 'publishing status']; // optional: names in the messages } } ``` ```php fails()) { return $this->apiError(422, 'Validation failed', ['errors' => $request->errors()]); } $data = $request->validated(); // only title and status return $this->created($data); } } ``` `POST /api/posts` with the JSON body `{"title": "Hello", "status": "draft", "admin": true}` answers 201 with `{"title":"Hello","status":"draft"}`; with `{"status": "archived"}` it answers 422 and lists the errors for `title` and `status`. - `authorize()` returning false stops the request with 403 before the action runs. Validation runs when the action first asks for it: check `fails()` to answer with your own response, as above. - `validated()` never returns input that failed the rules: it throws `Taphra\Exceptions\ValidationException`, an HTTP 422 whose `errors()` holds the messages. Saving `validated()` data is therefore safe even in an action that forgets `fails()`. - `validated()` returns only the fields named in `rules()`; `all()`, `get($key, $default)` and `has($key)` read the whole input; `errors()` returns the messages per field. - `attributes()` is optional: it returns readable names for the fields, which the messages use (`The selected publishing status is invalid.`), as [`Validator::attributes()`](#field-names-in-messages) does. --- Source: https://taphra.dev/docs/rest-apis/ # REST APIs This page covers JSON APIs: `RestController` and its response helpers, routes bound to HTTP methods, request bodies through a `FormRequest`, output shaped by an `ApiResource`, error responses, and `CrudController` for standard resources. It assumes you know [routing](routing.md) and [validation](requests.md). Every PHP example below marked as runnable runs as written, in order, against SQLite. ## Contents - [The table for these examples](#the-table-for-these-examples) - [JSON responses](#json-responses) - [Shaping output with ApiResource](#shaping-output-with-apiresource) - [Routes bound to methods](#routes-bound-to-methods) - [Request bodies and FormRequest](#request-bodies-and-formrequest) - [Errors](#errors) - [CRUD controllers](#crud-controllers) - [Generating a resource with make:crud](#generating-a-resource-with-makecrud) - [OpenAPI from annotations](#openapi-from-annotations) - [Authentication and CSRF for APIs](#authentication-and-csrf-for-apis) ## The table for these examples In an application the table comes from a migration (see [Database](database.md#migrations)). Here it is created directly: ```php use Taphra\DatabaseConnection; use Taphra\SchemaBuilder; $schema = new SchemaBuilder(DatabaseConnection::load('app_master')); $schema->dropIfExists('posts'); $schema->create('posts', function ($t) { $t->id(); $t->string('title'); $t->text('body')->nullable(); $t->string('status', 20)->default('draft'); $t->timestamps(); }); ``` ```php // app/DataStores/PostDataStore.php namespace App\DataStores; use Taphra\Traits\Timestamps; class PostDataStore extends AppDataStore { use Timestamps; public $objectName = 'posts'; protected $fillable = ['title', 'body', 'status']; } ``` ## JSON responses An API controller extends `Taphra\RestController`. Each helper sets the status code and `Content-Type: application/json; charset=utf-8`, turns off view rendering, and returns the body; the action returns it. | Helper | Response | |---|---| | `json(mixed $data, int $status = 200)` | `$data` as JSON (unescaped slashes and Unicode) | | `created(mixed $data = null, string $location = '')` | 201, with a `Location` header when given | | `noContent()` | 204, empty body | | `resource(string $resourceClass, array\|object $row, int $status = 200)` | one row through an `ApiResource` | | `collection(string $resourceClass, iterable $rows, int $status = 200)` | a JSON array of rows through an `ApiResource` | | `apiError(int $status, string $detail = '', array $extra = [], string $type = '', string $title = '')` | an RFC 7807 problem body (see [Errors](#errors)) | These helpers, like every method the base controller classes declare, are never URL actions: only the public methods your own controller declares are. ```php // app/Controllers/PostController.php namespace App\Controllers; use App\DataStores\PostDataStore; use App\Requests\PostRequest; use App\Resources\PostResource; use Taphra\RestController; class PostController extends RestController { public function index(): string { $posts = PostDataStore::where('status', 'published')->orderBy('id')->get(); return $this->collection(PostResource::class, $posts); } public function show(int $id): string { $post = PostDataStore::findById($id); if ($post === null) { return $this->apiError(404, "No post with id $id."); } return $this->resource(PostResource::class, $post); } public function store(PostRequest $request): string { if ($request->fails()) { return $this->apiError(422, 'The given data was invalid.', ['errors' => $request->errors()]); } $post = PostDataStore::create($request->validated()); return $this->created((new PostResource($post))->toArray(), '/api/posts/' . $post['id']); } public function destroy(int $id): string { (new PostDataStore())->delete(['id' => $id]); return $this->noContent(); } } ``` Route parameters arrive as action arguments in order; a parameter typed with a `FormRequest` subclass is filled from the request instead (next sections). ## Shaping output with ApiResource An `ApiResource` maps one row to the array the API returns, so the table's columns are not exposed by accident. Implement `transform(array $row): array`; the constructor takes an array or a `DataStoreRow`. ```php // app/Resources/PostResource.php namespace App\Resources; use Taphra\ApiResource; class PostResource extends ApiResource { public function transform(array $row): array { return [ 'id' => (int) $row['id'], 'title' => $row['title'], 'status' => $row['status'], 'links' => ['self' => '/api/posts/' . $row['id']], ]; } } ``` Outside a controller: `PostResource::make($row)->toArray()`, `PostResource::make($row)->toJson()`, and `PostResource::collection($rows)` for a list (an array of arrays). ## Routes bound to methods Bind each API route to its HTTP method in `app/Config/routes.yml`. The method sections (`GET:`, `POST:`, `PUT:`, `PATCH:`, `DELETE:`) sit at the top level of the file; `{id:\d+}` captures a parameter that must match the pattern. The target `post/show` runs `PostController::show()`. ```yaml GET: /api/posts: post/index /api/posts/{id:\d+}: post/show /api/crud/posts: postCrud/index /api/crud/posts/{id:\d+}: postCrud/show POST: /api/posts: post/store /api/crud/posts: postCrud/store PUT: /api/crud/posts/{id:\d+}: postCrud/update DELETE: /api/posts/{id:\d+}: post/destroy /api/crud/posts/{id:\d+}: postCrud/destroy ``` A request with another method on a declared path gets `405 Method Not Allowed` with an `Allow` header listing the methods that path accepts. The `/post/destroy` convention URL is refused the same way for a GET, because the routes bind `destroy` to DELETE only. Binding every state-changing action to POST, PUT, PATCH or DELETE keeps links and `` tags from reaching it. ## Request bodies and FormRequest A `FormRequest` declares the rules for one kind of input. Type-hint it on the action and the framework builds it from the request: query string, form fields, and a JSON body when `Content-Type` is `application/json`. Validation runs the first time you call `fails()`, `errors()` or `validated()`. `validated()` never returns input that failed: it throws a `ValidationException` (HTTP 422). ```php // app/Requests/PostRequest.php namespace App\Requests; use Taphra\FormRequest; class PostRequest extends FormRequest { public function rules(): array { return [ 'title' => 'required|min:3|max:200', 'body' => 'nullable|max:10000', 'status' => 'required|in:draft,published', ]; } public function authorize(): bool { return true; // for example: return \Taphra\Auth::check(); } } ``` | Method | Returns | |---|---| | `fails(): bool` | whether any rule failed | | `errors(): array` | messages per field, for example `['title' => ['...']]` | | `validated(): array` | the input fields that have a rule, and only those (check `fails()` first: it does not throw) | | `all(): array`, `get(string $key, mixed $default = null)`, `has(string $key): bool` | the raw merged input | When `authorize()` returns false the action does not run and the request ends with `403 Forbidden`. `Taphra\Request::input()` and the other `Request` accessors read the query string and form fields only. On the web entry a JSON body is decoded by a `FormRequest`; elsewhere read it with `json_decode(file_get_contents('php://input'), true)`. A JSON request against the routes above, sent in-process the way the [testing](testing.md) helpers send it: ```php $created = docs_request('POST', '/api/posts', ['title' => 'Hello API', 'body' => 'First post.', 'status' => 'published'], ['Content-Type' => 'application/json'], json: true); echo $created->getStatusCode(), "\n"; // 201 echo $created->getHeaderLine('Location'), "\n"; // /api/posts/1 echo $created->getBody(), "\n"; // {"id":1,"title":"Hello API","status":"published","links":{"self":"/api/posts/1"}} ``` (`docs_request()` is the helper these pages use to run examples; in your own tests use [HttpTestCase](testing.md).) Reading it back, directly and through the API: ```php use App\DataStores\PostDataStore; use App\Resources\PostResource; $post = PostDataStore::findById(1); echo PostResource::make($post)->toJson(), "\n"; // {"id":1,"title":"Hello API","status":"published","links":{"self":"/api/posts/1"}} echo docs_request('GET', '/api/posts')->getBody(), "\n"; // [{"id":1,"title":"Hello API","status":"published","links":{"self":"/api/posts/1"}}] ``` ## Errors `apiError()` answers with an [RFC 7807](https://www.rfc-editor.org/rfc/rfc7807) problem body. `type` defaults to `about:blank` and `title` to the standard phrase for the status; `$extra` is merged in. ```php $invalid = docs_request('POST', '/api/posts', ['title' => 'x'], ['Content-Type' => 'application/json'], json: true); echo $invalid->getStatusCode(), "\n"; // 422 echo $invalid->getBody(), "\n"; // {"type":"about:blank","title":"Unprocessable Entity","status":422,"detail":"The given data was invalid.", // "errors":{"title":["The title must be at least 3."],"status":["The status field is required."]}} echo docs_request('GET', '/api/posts/99')->getStatusCode(), "\n"; // 404 (from apiError) echo docs_request('DELETE', '/api/posts')->getStatusCode(), "\n"; // 405 echo docs_request('GET', '/api/posts/99')->getHeaderLine('Content-Type'), "\n"; // application/json; charset=utf-8 ``` Exceptions that reach the framework are answered by the app's error controller (`AppErrorController`), with the status taken from the exception: | Exception | Status | |---|---| | `Taphra\Exceptions\UnauthorizedException` | 401 | | `Taphra\Exceptions\ForbiddenException` (a failed CSRF check, `authorize()` returning false, a denied policy) | 403 | | `Taphra\Exceptions\NotFoundException`, `Taphra\Db\RecordNotFoundException` (from `findOrFail()`), an unknown controller or action | 404 | | `Taphra\Exceptions\MethodNotAllowedException` (a wrong method on a declared route) | 405, with `Allow` | | anything else | 500, logged | For a request that sends `Accept: application/json` (or `X-Requested-With: XMLHttpRequest`), the body is JSON: ```json {"error": true, "message": "Not Found", "code": 404} ``` In production the message is generic (`Not Found`, `Forbidden`, or `Internal Server Error` for every other status) so file names and queries never reach the client; in development it is the exception's message. Other requests get the `error404.tpl.php` or `error500.tpl.php` view. In development, the debug page shows the exception instead (and answers with status 500). Catch the exceptions you expect and answer with `apiError()` when an API needs a precise message for them. ## CRUD controllers `Taphra\CrudController` implements the five actions of a resource on top of a DataStore, a FormRequest and an ApiResource. You name the three classes; the actions are ordinary public methods you can override. | Action | Request | Response | |---|---|---| | `index()` | `GET`, with `?page=`, `?search=`, `?sort=`, `?dir=` | 200, `{"data": [...], "meta": {...}}` | | `show($id)` | `GET` | 200, the resource; 404 problem body when missing | | `store()` | `POST` | 201, the created resource; 422 with `errors` on invalid input | | `update($id)` | `PUT` or `PATCH` | 200, the updated resource; 404 or 422 | | `destroy($id)` | `DELETE` | 204; 404 when missing | CRUD controllers extend the app's own base class, `App\Controllers\AppCrudController` (a subclass of `Taphra\CrudController`, as `AppController` is for pages); the controllers `make:crud` writes extend it too. If your app does not have it yet, create it: ```php // app/Controllers/AppCrudController.php namespace App\Controllers; use Taphra\CrudController; abstract class AppCrudController extends CrudController { } ``` ```php // app/Controllers/PostCrudController.php namespace App\Controllers; use App\DataStores\PostDataStore; use App\Requests\PostRequest; use App\Resources\PostResource; class PostCrudController extends AppCrudController { protected function datastoreClass(): string { return PostDataStore::class; } protected function formRequestClass(): string { return PostRequest::class; } protected function resourceClass(): string { return PostResource::class; } protected function perPage(): int { return 10; } protected function searchable(): array { return ['title', 'body']; } protected function sortable(): array { return ['id', 'title', 'created_at']; } protected function defaultSort(): string { return 'id'; } protected function defaultSortDir(): string { return 'desc'; } protected function afterStore(array $row): void { // send a notification, clear a cache ... } } ``` The other settings are `indexConditions(): array` (fixed `WHERE` conditions for `index()`, such as `['user_id' => Auth::id()]`) and the hooks `afterUpdate(array $row)` and `afterDestroy(array $row)`. `?search=` runs a `LIKE` over the `searchable()` columns; `?sort=` accepts only the `sortable()` columns. Search and sort are off while those lists are empty. ```php docs_request('POST', '/api/crud/posts', ['title' => 'Second', 'status' => 'draft'], ['Content-Type' => 'application/json'], json: true); $list = json_decode((string) docs_request('GET', '/api/crud/posts?search=Second')->getBody(), true); print_r($list['meta']); // [total => 1, per_page => 10, current_page => 1, last_page => 1, has_more => false] $updated = docs_request('PUT', '/api/crud/posts/2', ['title' => 'Second, edited', 'status' => 'published'], ['Content-Type' => 'application/json'], json: true); echo $updated->getBody(), "\n"; // {"id":2,"title":"Second, edited","status":"published","links":{"self":"/api/posts/2"}} echo docs_request('DELETE', '/api/crud/posts/2')->getStatusCode(), "\n"; // 204 echo docs_request('GET', '/api/crud/posts/2')->getStatusCode(), "\n"; // 404 ``` `meta` carries the pagination numbers only; the rows in `data` always go through the ApiResource. `update()` and `destroy()` address the row by the key read from the database, never by the raw URL value. ## Generating a resource with make:crud ```bash php taphra make:crud Post php taphra make:crud Post --table=blog_posts ``` It writes four files, each a starting point to fill in: ``` app/DataStores/PostDataStore.php $objectName, commented $fillable and $casts app/Requests/PostFormRequest.php empty rules(), authorize() returning true app/Resources/PostResource.php transform() returning the id app/Controllers/PostCrudController.php the three class names ``` Then: 1. Make sure the app has `AppCrudController` (above). 2. Fill in `$fillable`, the rules and `transform()`. 3. Add the routes. The command prints a list of paths without HTTP methods (`/posts/store`, `/posts/:id/update` ...); bind them to methods instead, as in [Routes bound to methods](#routes-bound-to-methods), so a GET cannot reach `store()`, `update()` or `destroy()`. ## OpenAPI from annotations `php taphra route:openapi` writes an OpenAPI 3.0.3 description of the actions that carry `@Api*` docblock annotations, read from every PHP file under `app/Controllers/`: ```php // app/Controllers/PostController.php (annotated) /** * @ApiTag("Posts") * @ApiRoute(method="POST", path="/api/posts", summary="Create a post") * @ApiResponse(status=201, description="Created") * @ApiResponse(status=422, description="Invalid input") * @ApiSecurity("bearerAuth") */ public function store(PostRequest $request): string ``` ```bash php taphra route:openapi # docs/openapi.yaml php taphra route:openapi --format=json --output=public/openapi.json --title="Blog API" ``` The annotations are `@ApiRoute(method, path, summary)`, `@ApiParam(name, in, type, required, description)`, `@ApiResponse(status, description)`, `@ApiBody(description, required)`, `@ApiTag("...")` and `@ApiSecurity("bearerAuth")`. When an action takes a `FormRequest` and has no `@ApiBody`, its `rules()` become the request body schema: `required` fields are listed as required, `min`/`max` become `minLength`/`maxLength` and `in:` an `enum`. Actions without `@ApiRoute` are left out; the routes file is not read. ## Authentication and CSRF for APIs `RestController` does not check CSRF tokens (the skeleton turns the check on for `AppController`, the base of its HTML pages). That suits APIs that authenticate each request with a token, such as a JWT in the `Authorization` header: a browser does not add that header on its own. An API that relies on the session cookie instead must check a token, either by setting `protected $autoVerifyCsrf = true;` on its controllers or with the double-submit cookie. Both are in [Security](security.md#csrf). Protect routes with `AuthMiddleware` or a JWT middleware in a route group; see [Authentication](authentication.md). --- Source: https://taphra.dev/docs/database/ # Database This page covers connections, migrations, seeders and factories, transactions and raw SQL. Reading and writing rows is in [DataStores](datastores.md); building SQL by hand is in [SqlQuery](SqlQuery.md). Every PHP example below marked as runnable runs as written, in order, against SQLite; the commands in `bash` blocks run against the same app. ## Contents - [Connections](#connections) - [Migrations](#migrations) - [Seeders and factories](#seeders-and-factories) - [DataStore or SqlQuery](#datastore-or-sqlquery) - [Transactions](#transactions) - [Raw SQL on the connection](#raw-sql-on-the-connection) - [Input safety](#input-safety) ## Connections Connections are declared per environment in `app/Config/databases.yml`, under `dev`, `stg` and `prod`. Each key (here `app_master`) is a connection name; the skeleton's `AppDataStore` uses `app_master`, and a DataStore can name another one in its `$connection` property. ```yaml dev: app_master: type: sqlite host: "" port: "" name: tmp/app.sqlite # relative paths start at app/ user: "" password: "" prod: app_master: type: mysql # mysql | postgres | sqlite | mssql host: 127.0.0.1 port: 3306 name: myapp user: myapp password: "" charset: utf8mb4 persistent: true ``` Nothing connects until the first query. `mysql` (also MariaDB) needs `pdo_mysql`, `postgres` needs `pdo_pgsql`, `sqlite` needs `pdo_sqlite`, and `mssql` uses `pdo_dblib`. Redis and MongoDB connections are covered in [DataStores](datastores.md#other-backends). The YAML files are not templated: to keep a production password out of the repository, set it from the environment in `app/bootstrap.php`, which runs on every request after the configuration is loaded: ```php // app/bootstrap.php \Taphra\Config::set('databases.app_master.password', (string) getenv('DB_PASSWORD')); ``` `DatabaseConnection::load('app_master')` returns the connection object for code that needs it directly (the SchemaBuilder, SqlQuery, raw SQL). All DataStores on one connection name share one PDO handle per process, and `load()` returns that same connection: SQL run on it inside a [transaction](#transactions) is part of the transaction. It stays open for the process (in FrankenPHP worker mode, for the request) until `DataStore::flushConnections()`. Do not `close()` it while DataStores still use it: they hold the same object. After a `close()`, the next `load()` and the DataStores created after it open a new connection. Taphra's database lock, queue and session drivers open separate connections of their own, so their work stays out of the application's transactions. With `persistent: true`, PDO can hand such a connection the same pooled handle, which then shares an open transaction anyway; set `persistent: false` on a connection that needs separate handles. ## Migrations A migration is a PHP class in `app/Migrations/` that changes the schema one step forward (`up`) and back (`down`). Create one with: ```bash php taphra make:migration create_posts_table ``` The file is named `migration__.php`, where the id is a timestamp (`YYYYMMDDHHMMSS`) by default. Fill in `up()` and `down()` with the [SchemaBuilder](../packages/db/README.md): ```php create('posts', function ($t) { $t->id(); $t->string('title'); $t->text('body')->nullable(); $t->string('status', 20)->default('draft')->index(); $t->timestamps(); }); } public function down(array $args): void { (new SchemaBuilder(DatabaseConnection::load('app_master')))->dropIfExists('posts'); } } ``` For a change that is a single SQL statement, set the properties instead and leave the methods out: `$up` and `$down` hold the SQL, `$connection` the connection name. ```php create('projects', function ($t) { $t->id(); $t->integer('client_id'); $t->string('title'); $t->foreign('client_id', 'clients', 'id', 'CASCADE'); // ON DELETE CASCADE ON UPDATE RESTRICT }); ``` `foreign($columns, $refTable, $refColumns = 'id', $onDelete = 'RESTRICT', $onUpdate = 'RESTRICT', $name = null)` takes the same arguments as `addForeignKey()` without the table. Pass arrays for a key of several columns. The actions are `CASCADE`, `RESTRICT`, `SET NULL`, `SET DEFAULT` and `NO ACTION`. SQL Server has no `RESTRICT`, so there it is written `NO ACTION`, which also refuses the change. MySQL (InnoDB) rejects `SET DEFAULT`, so `create()` on a MySQL connection throws an `InvalidArgumentException` for it instead of putting another action in its place. The constraint is named `fk__` unless you give a name; a default name longer than 63 bytes is shortened with a hash, at a character boundary, to fit PostgreSQL and MySQL. Give the column the type of the column it references: `integer()` for a table whose key is `id()`. To add a foreign key to a table that exists, `$schema->addForeignKey('projects', 'client_id', 'clients', 'id', 'CASCADE')` works on MySQL, PostgreSQL and SQL Server. SQLite cannot add one to an existing table, so there it throws an `InvalidArgumentException` that points to `foreign()`: declare the key when the table is created, or create the table again. **SQLite checks foreign keys only when they are turned on.** SQLite stores the foreign key with the table but enforces it only on a connection that ran `PRAGMA foreign_keys = ON`, and each new connection starts with it off. Taphra leaves SQLite's default as it is. To turn the checks on, add the pragma to the connection's `extra` settings; Taphra runs `PRAGMA foreign_keys = ON` each time it opens that connection: ```yaml # app/Config/databases.yml dev: app_master: type: sqlite host: "" port: "" name: tmp/app.sqlite user: "" password: "" extra: pragma.foreign_keys: "ON" ``` Any `pragma.` key of an SQLite connection's `extra` runs `PRAGMA = ` the same way. MySQL (InnoDB), PostgreSQL and SQL Server enforce foreign keys by default. ### Where the migration state lives `app/Config/migrations.yml` chooses where the list of migrations that ran is kept: ```yaml path: null # null: app/Migrations/ id_format: timestamp # or sequential (1, 2, 3 ...) state: backend: file # file: app/Migrations/migration_state.json database: # backend: database keeps it in a table instead connection: app_master table: schema_migrations ``` The `file` backend suits one developer. With `backend: database` the state travels with the database, so every developer and every deploy sees the same list; the table is created on first use. Switching backends does not copy the existing state. ### Migrations from more folders A Composer package can ship migrations, and an app can keep some of its own in another folder (a module, say). Each extra folder has a name. A package adds its folder from its [service provider](container.md#service-providers), which the console boots before a command runs: ```php .json` next to the app's state file; the `database` backend uses the table `
_` (`schema_migrations_acme_blog`). The app's own state is unchanged, so an app with one folder works as before. - **Same file names:** a file with the same name in two folders is two migrations. PHP cannot load two classes with the same name, so a package declares a namespace in its migration files (`namespace Acme\Blog\Migrations;`); the class is then `Acme\Blog\Migrations\Migrate_migration__`. Two files of the same name without a namespace stop the command with an error that says so. - **Names:** lower-case letters, digits and underscores, starting with a letter, at most 40 characters, and not `app`. One name is one folder; a missing folder stops the command with an error. The output names the folder of each migration that is not the app's: ``` Running UP migration 20260101000000: CreatePostsTable Running UP migration 20260115000000 (acme_blog): CreateBlogPosts ``` and `migrate:status` adds a Folder column: ``` -- state: 2 migration(s) ran | latest: 20260115000000 | batch: 1 | backend: file | folders: app, acme_blog ID Status Folder Description --------------------------------------------------------------------- 20260101000000 Ran app CreatePostsTable 20260115000000 Ran acme_blog CreateBlogPosts ``` ## Seeders and factories A factory describes a typical row; a seeder uses factories (or plain inserts) to fill tables. Both are generated: ```bash php taphra make:factory Post # app/Factories/PostFactory.php php taphra make:seeder Post # app/Seeds/PostSeeder.php ``` ```php ```php "Post number $n", 'body' => 'Lorem ipsum.', 'status' => 'draft', ]; } public function published(): self { return $this->state(fn (array $attrs) => ['status' => 'published']); } } ``` `make()` returns the attributes without saving (an array of arrays after `count()`); `create()` fills a DataStore through `$fillable` and saves it. `state()` returns a copy with overrides applied after `definition()`; arguments to `make()` and `create()` are applied last. ```php count(5)->create(); (new PostFactory())->published()->count(2)->create(); $this->info('7 posts seeded.'); } } ``` `php taphra db:seed` runs `App\Seeds\DatabaseSeeder`, which calls the others in order: ```php call([PostSeeder::class]); } } ``` ```bash php taphra db:seed # DatabaseSeeder php taphra db:seed --class=PostSeeder # one seeder php taphra migrate:reset && php taphra db:seed # start again from empty tables ``` After `php taphra db:seed`: ```php use App\DataStores\PostDataStore; use App\Factories\PostFactory; echo PostDataStore::all()->count(), "\n"; // 7 echo PostDataStore::where('status', 'published')->count(), "\n"; // 2 $attrs = (new PostFactory())->make(['title' => 'Not saved']); echo $attrs['title'], ' / ', $attrs['status'], "\n"; // Not saved / draft ``` ## DataStore or SqlQuery Use a **DataStore** (one class per table) for application data: it binds values, applies `$fillable`, casts, timestamps and soft deletes, and loads relations. Use **SqlQuery** when a query does not belong to one table: reports, joins across many tables, CTEs, window functions, set operations. Both bind every value. Each has its own page: [DataStores](datastores.md), [SqlQuery](SqlQuery.md). ## Transactions `DataStore::transaction()` runs a callable inside a transaction on the DataStore's connection: it commits when the callable returns, and rolls back and rethrows when it throws. It returns what the callable returns. ```php use App\DataStores\PostDataStore; $id = PostDataStore::transaction(function () { $post = PostDataStore::create(['title' => 'Kept', 'status' => 'draft']); PostDataStore::create(['title' => 'Kept too', 'status' => 'draft']); return $post['id']; }); try { PostDataStore::transaction(function () { PostDataStore::create(['title' => 'Rolled back', 'status' => 'draft']); throw new RuntimeException('payment failed'); }); } catch (RuntimeException $e) { echo $e->getMessage(), "\n"; // payment failed } echo PostDataStore::where('title', 'Rolled back')->count(), "\n"; // 0 echo PostDataStore::all()->count(), "\n"; // 9 ``` Every DataStore on the same connection shares the transaction, because they share one PDO handle; so does raw SQL on `DatabaseConnection::load()` for that connection name. Transactions do not nest: call `transaction()` once, at the outer level. On the connection object the same steps are `beginTransaction()`, `commit()` and `rollback()`. ## Raw SQL on the connection For a statement neither API covers, the connection runs SQL with `?` placeholders and binds the values: ```php use Taphra\DatabaseConnection; $db = DatabaseConnection::load('app_master'); // query($sql, $returnAll = true, $withAliases = true, array $params = []) $rows = $db->query('SELECT status, COUNT(*) AS n FROM posts WHERE id > ? GROUP BY status ORDER BY status', true, false, [0]); print_r($rows); // [['status' => 'draft', 'n' => 7], ['status' => 'published', 'n' => 2]] $one = $db->query('SELECT title FROM posts WHERE id = ?', false, false, [1]); echo $one['title'], "\n"; // Post number 1 // execute($sql, array $params = []) for writes: returns the number of rows changed echo $db->execute('UPDATE posts SET status = ? WHERE title = ?', ['published', 'Kept']), "\n"; // 1 echo $db->execute('UPDATE posts SET status = ? WHERE title = ?', ['published', 'No such post']), "\n"; // 0 ``` Pass `false` as `$withAliases` to get flat rows; with `true` (the default) each row is grouped by table name. `execute()` returns the number of rows the statement changed, as the database reports it, with or without parameters. A conditional update can use it to tell whether it applied: `UPDATE ... WHERE status = 'pending'` returns 0 when another request changed the row first. MySQL counts the rows whose values actually changed, so an UPDATE that sets the values a row already has returns 0 there. ## Input safety The database layer is built so that request data cannot change the shape of a query: - Values are always bound as parameters: in DataStore conditions, the query builder, `Criteria`, SqlQuery, and the raw SQL methods above. - Identifiers and operators are checked. Column names in conditions, `orderBy()`, `groupBy()` and JSON paths must be plain names (`title`, `posts.title`); operators must come from a fixed list (`=`, `<`, `LIKE`, `IN`, `BETWEEN`, `IS NULL` ...). Anything else throws before a query is built. - SQL text goes in only where you write it: the `*Raw()` methods (`whereRaw()`, `selectRaw()`, `orderByRaw()` ...), string conditions such as `find('views > 10')`, and the connection's `query()` and `execute()`. Write those in code; pass request values as their bindings. - `$fillable` and `$guarded` decide which keys `fill()`, `create()` and the write methods accept from an input array. ```php use App\DataStores\PostDataStore; use Taphra\Db\DataStoreException; use Taphra\Db\DbException; $sort = 'title; DROP TABLE posts'; // as if it came from ?sort= try { PostDataStore::where('status', 'draft')->orderBy($sort)->get(); } catch (DataStoreException $e) { echo "refused: invalid column name\n"; } try { PostDataStore::where('title', 'OR 1=1 --', 'x')->get(); } catch (DbException $e) { echo "refused: operator not allowed\n"; } // A value is only ever a value: echo PostDataStore::where('title', "' OR '1'='1")->count(), "\n"; // 0 ``` `findOrFail()` throws `Taphra\Db\RecordNotFoundException` when nothing matches, and the framework answers an uncaught one with `404 Not Found`: ```php // app/Controllers/PostController.php namespace App\Controllers; use App\DataStores\PostDataStore; use Taphra\RestController; class PostController extends RestController { public function show(int $id): string { $post = (new PostDataStore())->findOrFail(['id' => $id])->first(); return $this->json($post); } } ``` ```yaml GET: /posts/{id:\d+}: post/show ``` ```php echo docs_request('GET', '/posts/1')->getStatusCode(), "\n"; // 200 echo docs_request('GET', '/posts/999')->getStatusCode(), "\n"; // 404 ``` The full list of input rules, including what `$fillable` does and does not filter, is in [DataStores: input safety](datastores.md#input-safety). --- Source: https://taphra.dev/docs/datastores/ # DataStores A DataStore is a class for one database table. It reads and writes rows, builds queries, applies casts, mass-assignment rules, timestamps and soft deletes, and loads related rows. This page covers DataStores inside a Taphra application. The same classes work without the framework: see [packages/db/README.md](../packages/db/README.md), which also lists the SchemaBuilder and SqlQuery APIs in full. Every PHP example below runs as written, in order, against SQLite. ## Contents - [Connections](#connections) - [Defining a DataStore](#defining-a-datastore) - [Creating, reading, updating, deleting](#creating-reading-updating-deleting) - [The query builder](#the-query-builder) - [Rows and collections](#rows-and-collections) - [Casts](#casts) - [Timestamps and soft deletes](#timestamps-and-soft-deletes) - [Relations and eager loading](#relations-and-eager-loading) - [Scopes](#scopes) - [Global filters](#global-filters) - [Hooks](#hooks) - [Observers](#observers) - [Pagination](#pagination) - [Input safety](#input-safety) - [Other backends](#other-backends) --- ## Connections Connections are declared per environment in `app/Config/databases.yml`. A DataStore names one with its `$connection` property; the skeleton's `AppDataStore` uses `app_master`. ```yaml dev: app_master: type: mysql # mysql | postgres | sqlite | mssql host: 127.0.0.1 port: 3306 name: myapp_dev user: root password: "" charset: utf8mb4 ``` A SQLite connection uses `type: sqlite`, an empty `host` and `port`, and the database file path as `name` (relative paths are resolved against the app directory). Tables are created in migrations (`php taphra make:migration create_posts_table`, then `php taphra migrate`) with the SchemaBuilder. These examples create them directly: ```php use Taphra\DatabaseConnection; use Taphra\SchemaBuilder; $schema = new SchemaBuilder(DatabaseConnection::load('app_master')); foreach (['comments', 'posts', 'users'] as $table) { $schema->dropIfExists($table); } $schema->create('users', function ($t) { $t->id(); $t->string('name', 100); $t->string('email')->unique(); $t->string('role', 20)->default('author'); }); $schema->create('posts', function ($t) { $t->id(); $t->integer('user_id'); $t->string('title'); $t->text('body')->nullable(); $t->string('status', 20)->default('draft'); $t->boolean('is_featured')->default(false); $t->integer('views')->default(0); $t->text('meta')->nullable(); $t->timestamps(); $t->softDeletes(); }); $schema->create('comments', function ($t) { $t->id(); $t->integer('post_id'); $t->text('body'); $t->boolean('approved')->default(false); }); ``` --- ## Defining a DataStore DataStores live in `app/DataStores/`, in the `App\DataStores` namespace, and extend `AppDataStore`. ```php namespace App\DataStores; use Taphra\DataStoreQueryBuilder; use Taphra\Traits\SoftDeletes; use Taphra\Traits\Timestamps; class UserDataStore extends AppDataStore { public $objectName = 'users'; // the table protected $fillable = ['name', 'email']; // accepted from input } class PostDataStore extends AppDataStore { use Timestamps; // created_at / updated_at use SoftDeletes; // deleted_at public $objectName = 'posts'; protected $fillable = ['user_id', 'title', 'body', 'status', 'meta']; protected $casts = [ 'is_featured' => 'bool', 'views' => 'int', 'meta' => 'json', ]; public function scopePublished(DataStoreQueryBuilder $q): DataStoreQueryBuilder { return $q->where('status', 'published'); } public function comments() { return $this->hasMany(CommentDataStore::class, 'post_id'); } public function author() { return $this->belongsTo(UserDataStore::class, 'user_id'); } } class CommentDataStore extends AppDataStore { public $objectName = 'comments'; protected $fillable = ['post_id', 'body']; } ``` `$connection` and `$objectName` must be `public`. The primary key is read from the table; declare `public $primaryKey = 'id';` (or `['post_id', 'tag_id']`) for tables or views without one. `php taphra make:crud Post --table=posts` writes a DataStore, a FormRequest, an ApiResource and a CrudController for a table. --- ## Creating, reading, updating, deleting ```php use App\DataStores\CommentDataStore; use App\DataStores\PostDataStore; use App\DataStores\UserDataStore; // create() fills through $fillable, inserts, and returns the stored row. $alice = UserDataStore::create(['name' => 'Alice', 'email' => 'alice@example.com']); $post = PostDataStore::create(['user_id' => $alice['id'], 'title' => 'Hello', 'status' => 'published', 'meta' => ['color' => 'blue']]); // insert() / save() take an array and return the new primary key. save() runs // the beforeSave() hooks (casts, Timestamps); insert() does not. $ds = new PostDataStore(); $id = $ds->insert(['user_id' => $alice['id'], 'title' => 'Draft one']); $ds->save(['user_id' => $alice['id'], 'title' => 'Draft two']); (new CommentDataStore())->insert(['post_id' => $post['id'], 'body' => 'First!']); // Read $one = PostDataStore::findById($post['id']); // ?DataStoreRow $first = PostDataStore::firstWhere(['status' => 'published']); $all = PostDataStore::all(); // DataStoreCollection $some = $ds->find(['status' => 'draft'], 10, 0, 'id', 'DESC'); // conditions, limit, offset, order column, direction $n = $ds->findCount(['status' => 'draft']); $found = $ds->exists(['title' => 'Hello']); // Update through the row (only changed columns, updated_at set)... $one->title = 'Hello, world'; $one->save(); // ...by key... $ds->update(['id' => $id], ['title' => 'Draft one (edited)']); // ...or every matching row. $ds->update(['status' => 'draft'], ['body' => 'Not written yet']); // Delete (soft delete here: PostDataStore uses SoftDeletes) $ds->delete(['id' => $id]); PostDataStore::firstWhere(['title' => 'Draft two'])->delete(); // Insert or update on a unique key (new UserDataStore())->upsert(['name' => 'Alice A.', 'email' => 'alice@example.com'], ['email']); // findOrFail() throws Taphra\Db\RecordNotFoundException; a Taphra app answers it with a 404. try { $ds->findOrFail(['id' => 999]); } catch (\Taphra\Db\RecordNotFoundException $e) { } // Several writes in one transaction (all DataStores on a connection share one handle) PostDataStore::transaction(function () use ($alice) { $p = PostDataStore::create(['user_id' => $alice['id'], 'title' => 'Atomic', 'status' => 'draft']); (new CommentDataStore())->insert(['post_id' => $p['id'], 'body' => 'Same transaction']); }); ``` Batch writes: `insertBatch($rows)` and `upsertBatch($rows, $conflictColumns)` send many rows per statement. The active-record style (`resetRecord()`, `fill()`, `save()`, `read($id)`, `get($field)`) is described in the package README. --- ## The query builder Static calls start a builder; `(new PostDataStore())->query()` returns one too. ```php use App\DataStores\PostDataStore; $posts = PostDataStore::where('status', 'published') ->where('views', '>=', 0) ->whereIn('user_id', [1, 2]) ->orderBy('created_at', 'desc') ->limit(10) ->get(); // DataStoreCollection $latest = PostDataStore::where('status', 'published')->orderBy('id', 'desc')->first(); $count = PostDataStore::where('status', 'published')->count(); $views = PostDataStore::where('user_id', 1)->sum('views'); $titles = PostDataStore::where('user_id', 1)->pluck('title'); $matching = (new PostDataStore())->query()->whereContains(['title', 'body'], 'hello')->get(); $perUser = (new PostDataStore())->query()->selectRaw('user_id, COUNT(*) AS n')->groupBy('user_id')->get(); $long = PostDataStore::whereRaw('LENGTH(title) > ?', [3])->get(); $blue = PostDataStore::jsonPath('meta', 'color', '=', 'blue')->get(); $active = PostDataStore::whereHas('comments', 'post_id')->get(); $counted = PostDataStore::withCount('comments', 'post_id')->get(); (new PostDataStore())->query()->orderBy('id')->chunk(100, function ($batch) { // ... }); echo PostDataStore::where('status', 'published')->toSql(); // for logs and debugging ``` On a grouped query (`groupBy()` or `having()`), `count()` counts the groups, and `sum()`, `avg()`, `min()` and `max()` throw a `DbException` rather than return one group's value: select the aggregate with `selectRaw()` and read one value per group with `get()`, as `$perUser` does above. The full list of builder methods is in the package README. --- ## Rows and collections ```php use App\DataStores\PostDataStore; $posts = PostDataStore::all(); $post = $posts->first(); $post['title']; // array access $post->title; // property access $post->title = 'Renamed'; $post->isDirty('title'); // true $post->getDirty(); // ['title' => 'Renamed'] $post->getOriginal('title'); $post->refresh(); // reload, dropping the change $post->only(['id', 'title']); $post->except(['body']); $post->toArray(); json_encode($post); count($posts); $posts->isEmpty(); $posts->filter(fn ($p) => $p['views'] > 0); $posts->map(fn ($p) => $p['title']); $posts->keyBy('id'); $posts->each(function ($p) {}); $posts->toArray(); // array of DataStoreRow $posts->toJson(); // same as json_encode($posts): a JSON list of the rows ``` --- ## Casts `$casts` converts columns when rows are read and when a row is saved with `save()` (the active record, an array passed to `save($data)`, or a `DataStoreRow`). `insert()`, `update()` and `upsert()` do not apply them (on an SQL connection a PHP array is still stored as JSON). Types: `bool`/`boolean`, `int`/`integer`, `float`/`double`, `string`, `array`/`json` (decoded to an array), `object` (decoded to an object), `datetime` (a `DateTime`). ```php use App\DataStores\PostDataStore; $post = PostDataStore::firstWhere(['title' => 'Hello, world']); var_dump($post['is_featured']); // bool(false) var_dump($post['meta']['color']); // string(4) "blue" ``` --- ## Timestamps and soft deletes `Timestamps` sets `created_at` on insert and `updated_at` on every save: the active record, an array passed to `save($data)`, and `DataStoreRow::save()`. A new row gets both, also when its record was filled without `resetRecord()` first. `insert()` and `update()` run no hooks, so they do not set them. Rename the columns with `protected $createdAtColumn` / `$updatedAtColumn`, or store Unix times with `protected $timestampFormat = 'unix';`. Its `beforeSave()` then calls the parent class's `beforeSave()`, so casts (an `object` or `array` column stored as JSON) and your base class's hook still run. `SoftDeletes` makes `delete()` set `deleted_at`. Every read (`find()`, `findCount()`, `exists()`, the query builder's `get()`, `count()`, `sum()`, `paginate()`) leaves deleted rows out. ```php use App\DataStores\PostDataStore; $ds = new PostDataStore(); $ds->delete(['title' => 'Atomic']); $ds->findCount(['title' => 'Atomic']); // 0 $ds->withTrashed()->findCount(['title' => 'Atomic']); // 1 $ds->onlyTrashed()->find(); // just the deleted rows $ds->restore(['title' => 'Atomic']); // deleted_at back to NULL $ds->forceDelete(['title' => 'Atomic']); // a real DELETE ``` `withTrashed()` and `onlyTrashed()` apply to the next query run on that DataStore instance, or to a whole query-builder query started from it: `$ds->withTrashed()->query()->paginate(20)`. --- ## Relations and eager loading `hasMany()`, `hasOne()`, `belongsTo()` and `belongsToMany()` declare relations. Name the related DataStore by class (`CommentDataStore::class`) or by short name (`'comment'` finds `CommentDataStore` in the same namespace, then the global one). `DataStoreCollection::load()` fetches a relation for every row of a collection in one query, so a list page does not run one query per row: ```php use App\DataStores\PostDataStore; $posts = PostDataStore::published()->get(); $posts->load('comments', 'author'); // two queries in total foreach ($posts as $post) { $comments = $post->getRelation('comments'); // DataStoreCollection $author = $post->getRelation('author')?->first(); $post->relationLoaded('comments'); // true } ``` `load()` supports `hasMany`, `hasOne` and `belongsTo`. Calling a relation method on a DataStore only declares the relation; it does not run a query. Two more relation helpers return rows directly (call them from a method on the DataStore, after `read()`): - `hasManyVia($targetClass, $pivotClass, $firstKey, $secondKey)`: rows two hops away, for example a country's posts through its users. - `polymorphicChildren($relatedClass, $morphName)`, `polymorphicChild()` and `polymorphicParent($morphName)`: rows linked by `_type` and `_id` columns. Register the type values first with `DataStore::registerPolymorphicTypes(['post' => PostDataStore::class])`; class names are never stored. --- ## Scopes A public method named `scope()` becomes a static entry point. If its first parameter is a `DataStoreQueryBuilder`, it receives a fresh builder; other parameters come from the call. ```php namespace App\DataStores; use Taphra\DataStoreQueryBuilder; class ArticleDataStore extends AppDataStore { public $objectName = 'posts'; public function scopePublished(DataStoreQueryBuilder $q): DataStoreQueryBuilder { return $q->where('status', 'published'); } public function scopeByUser(DataStoreQueryBuilder $q, int $userId): DataStoreQueryBuilder { return $q->where('user_id', $userId); } public function scopeRecent(): DataStoreQueryBuilder { return $this->query()->orderBy('created_at', 'desc'); } } ``` ```php use App\DataStores\ArticleDataStore; $a = ArticleDataStore::published()->orderBy('id')->get(); $b = ArticleDataStore::byUser(1)->count(); $c = ArticleDataStore::recent()->limit(5)->get(); ``` A scope must return a `DataStoreQueryBuilder`; anything else throws a `DataStoreException`. --- ## Global filters A filter is a named condition added to every query-builder query on a class. Filters can be skipped one by one. ```php use App\DataStores\PostDataStore; PostDataStore::addFilter('published', fn ($q) => $q->where('status', 'published')); $visible = PostDataStore::where('user_id', 1)->get(); // published rows only $all = PostDataStore::unfiltered()->get(); // every filter skipped $drafts = PostDataStore::unfiltered('published')->where('status', 'draft')->get(); PostDataStore::removeFilter('published'); PostDataStore::flushFilters(); ``` Filters apply to the query builder (`where()`, `get()`, `count()`, `sum()`, `paginate()` and the rest), not to `find()`, `findById()` or `all()`. --- ## Hooks Override these public methods on a DataStore. Call the parent method in `beforeSave()` and `afterFind()`: casts (and the `Timestamps` and `SoftDeletes` traits) work through them. | Method | Called | Return | |---|---|---| | `beforeFind(mixed &$conditions): bool` | before `find()` and `findCount()`, and once per query-builder query | `false` cancels the query | | `afterFind(mixed $conditions, mixed &$result): void` | after `find()`, on the raw rows | | | `beforeSave(mixed $data): bool` | before `save()` inserts or updates. The values being saved are in `$this->activeRecord`, also for `save($data)` with an array, and what the hook changes there is saved | `false` cancels the save: nothing is written, `afterSave()` does not run, `save()` returns `false` and `create()` throws `Taphra\Db\DataStoreException` | | `afterSave(mixed $data, mixed $result): void` | after `save()` | | | `beforeDelete(mixed $criteria): bool` | before `delete()` | `false` cancels the delete | | `afterDelete(mixed $criteria, mixed $result): void` | after `delete()` | | ```php namespace App\DataStores; class AuditedPostDataStore extends AppDataStore { public $objectName = 'posts'; public array $log = []; public function beforeDelete(mixed $criteria): bool { $this->log[] = 'deleting'; return true; } public function afterSave(mixed $data, mixed $result): void { $this->log[] = 'saved'; } } ``` ```php use App\DataStores\AuditedPostDataStore; $audited = new AuditedPostDataStore(); $audited->save(['user_id' => 1, 'title' => 'Audited']); $audited->delete(['title' => 'Audited']); // $audited->log === ['saved', 'deleting'] ``` --- ## Observers Observers react to the same events from outside the DataStore class: any object with `afterSave()`, `afterDelete()` and/or `afterFind()` methods. They run after the hooks, in registration order, and are kept per DataStore class. ```php use App\DataStores\CommentDataStore; class CommentCounter { public int $saved = 0; public function afterSave(mixed $data, mixed $result): void { $this->saved++; } } $counter = new CommentCounter(); CommentDataStore::observe($counter); // an instance, or a class name (new CommentDataStore())->save(['post_id' => 1, 'body' => 'Observed']); // $counter->saved === 1 CommentDataStore::flushObservers(); // e.g. in a test's setUp() ``` Register observers once at boot, for example in a service provider's `boot()` method. --- ## Pagination ```php use App\DataStores\PostDataStore; use Taphra\Http\ListQuery; $page = PostDataStore::paginate(20); // reads ?page $page = PostDataStore::where('status', 'published')->paginate(20, 1); $page->items; // rows on this page $page->total; // rows on every page $page->lastPage; $page->hasMore; $page->meta(); // the numbers only, for an API response // An index action: ?search=, ?sort=, ?dir= and ?page= from the request $list = ListQuery::fromRequest() ->searchable(['title', 'body']) ->sortable(['title', 'created_at'], 'created_at', 'desc') ->paginate(new PostDataStore(), 20); ``` In a view, `$html->pagination($list, '/posts')` renders the page links. `CrudController` builds JSON index, show, store, update and destroy actions on top of these. --- ## Input safety - Values are bound as `?` parameters everywhere: `where()`, array conditions (`find(['email' => $email])`), `Criteria`, and the array conditions of `update()` and `delete()`. - Condition keys, `orderBy()`, `groupBy()` and JSON paths accept column names only; operators come from a fixed list; LIMIT and OFFSET are integers. - String conditions (`find('views > 10')`), `where('raw SQL')` and the `*Raw()` methods are SQL: write them in code, never from request data. - Condition arrays need column-name keys; an integer key may only carry a `Criteria` object. - `findById()` rejects array ids such as `?id[]=`; a composite id must name exactly the primary-key columns. - With `$fillable` declared, a primary key in `save($data)` that is not fillable is dropped: the call inserts instead of updating that row. Update by key with `update(['id' => $id], $data)`. - `$fillable` / `$guarded` filter `fill()`, `create()`, and (when the DataStore declares either) the data passed to `save()`, `insert()`, `update()` and `upsert()`. Values set on a row or through `forceFill()` are not filtered. - `$fillable` names are matched exactly. `$guarded` names are matched in any case (MySQL, MariaDB and SQLite read `ROLE` as the column `role`), and with `$guarded` a key that is not a column spelled as in the table's schema is dropped. --- ## Other backends This page covers SQL databases (SQLite, MySQL/MariaDB, PostgreSQL; SQL Server statements are generated but not tested against a server). The package also ships `RedisConnection` and an experimental `MongodbConnection`, which are not covered here. DataStores on MongoDB are not supported in 1.0: use `MongodbConnection` directly, and expect it to change. The query builder, relations, SchemaBuilder and SqlQuery are SQL only. --- Source: https://taphra.dev/docs/sqlquery/ # SqlQuery `SqlQuery` builds one SQL statement: SELECT (with joins, grouping, sub-queries, CTEs, set operations and window functions), INSERT, UPDATE, DELETE or an upsert. Use it for statements that do not map to one DataStore; for single-table work the DataStore query builder ([datastores.md](datastores.md)) is shorter. The DataStore query builder uses `SqlQuery` internally. Values are bound as `?` parameters. Column names given to `orderBy()`, `groupBy()` and condition arrays are checked and quoted for the connection's database (MySQL/MariaDB, PostgreSQL, SQLite; SQL Server statements are generated but not tested against a server). Every PHP example below runs as written, in order, against SQLite. ## Contents - [Setup](#setup) - [SELECT](#select) - [Conditions](#conditions) - [Joins](#joins) - [Grouping, ordering, limits](#grouping-ordering-limits) - [Raw SQL fragments](#raw-sql-fragments) - [Sub-queries](#sub-queries) - [Common table expressions](#common-table-expressions) - [Set operations](#set-operations) - [Window functions](#window-functions) - [INSERT, UPDATE, DELETE, upsert](#insert-update-delete-upsert) - [Row locking](#row-locking) - [Running SQL on the connection](#running-sql-on-the-connection) - [Inspecting a statement](#inspecting-a-statement) --- ## Setup `SqlQuery` takes a connection. In a Taphra app, `DatabaseConnection::load()` returns one by name from `app/Config/databases.yml`: the same connection the DataStores on that name use, also returned by `$ds->connectionManager->getConnection()`. ```php use Taphra\DatabaseConnection; use Taphra\SchemaBuilder; $conn = DatabaseConnection::load('app_master'); $schema = new SchemaBuilder($conn); foreach (['orders', 'employees', 'customers'] as $table) { $schema->dropIfExists($table); } $schema->create('customers', function ($t) { $t->id(); $t->string('name', 100); $t->string('email')->unique(); $t->boolean('active')->default(true); }); $schema->create('orders', function ($t) { $t->id(); $t->integer('customer_id'); $t->decimal('total', 10, 2); $t->string('status', 20)->default('new'); $t->dateTime('created_at'); }); $schema->create('employees', function ($t) { $t->id(); $t->string('name', 100); $t->string('dept', 50); $t->integer('salary'); $t->integer('manager_id')->nullable(); }); $conn->execute("INSERT INTO customers (name, email, active) VALUES ('Ann', 'ann@example.com', 1), ('Ben', 'ben@example.com', 1), ('Cy', 'cy@example.com', 0)"); $conn->execute("INSERT INTO orders (customer_id, total, status, created_at) VALUES (1, 120.00, 'paid', '2026-01-05 10:00:00'), (1, 30.50, 'paid', '2026-02-01 09:00:00'), (2, 75.00, 'new', '2026-02-03 12:00:00'), (3, 10.00, 'cancelled', '2026-02-04 08:00:00')"); $conn->execute("INSERT INTO employees (name, dept, salary, manager_id) VALUES ('Eve', 'eng', 120, NULL), ('Finn', 'eng', 100, 1), ('Gus', 'eng', 90, 2), ('Hal', 'ops', 80, 1)"); ``` --- ## SELECT ```php use Taphra\SqlQuery; $rows = (new SqlQuery($conn)) ->select(['id', 'name']) // a list of columns; select('name', 'alias') sets one column and its alias ->from('customers') ->fetch(true, false); // all rows, flat: [['id' => 1, 'name' => 'Ann'], ...] $one = (new SqlQuery($conn))->select('*')->from('customers')->where(['id' => 1])->fetch(false, false); // one row $distinct = (new SqlQuery($conn))->select('status')->distinct()->from('orders')->fetch(true, false); $totals = (new SqlQuery($conn)) ->select('customer_id') ->selectRaw('SUM(total) AS spent, COUNT(*) AS n') ->from('orders') ->groupBy('customer_id') ->fetch(true, false); ``` `fetch($all, $withAliases)`: with `$withAliases = true` (the default) each row is grouped by table name, `[['customers' => ['id' => 1, ...]]]`; pass `false` for plain rows. --- ## Conditions `where()` takes a `Criteria`, an array, or a raw SQL string. Calling it again ANDs the new conditions. ```php use Taphra\Criteria; use Taphra\SqlQuery; // Array: column => value, with an optional operator in the key $rows = (new SqlQuery($conn))->select('*')->from('orders') ->where(['status' => 'paid', 'total >=' => 50, 'customer_id in' => [1, 2]]) ->fetch(true, false); // Criteria: field, operator, value $rows = (new SqlQuery($conn))->select('*')->from('orders') ->where(new Criteria('status', '!=', 'cancelled')) ->where(new Criteria('created_at', '>=', '2026-02-01')) ->fetch(true, false); // Groups: status = 'paid' AND (total > 100 OR customer_id = 2) $c = new Criteria('status', '=', 'paid'); $c->orGroup(function (Criteria $g) { $g->add('total', '>', 100); $g->add('customer_id', '=', 2); }); $rows = (new SqlQuery($conn))->select('*')->from('orders')->where($c)->fetch(true, false); // BETWEEN, IN, IS NULL $rows = (new SqlQuery($conn))->select('*')->from('employees') ->where(new Criteria('salary', 'BETWEEN', [85, 110])) ->where(new Criteria('manager_id', 'IS NOT NULL')) ->fetch(true, false); // A server-side expression as the value: SqlRawExpr is written as SQL, not bound $rows = (new SqlQuery($conn))->select('*')->from('orders') ->where(new Criteria('created_at', '<=', $conn->now())) // NOW(), datetime('now') or GETDATE() ->fetch(true, false); ``` Allowed operators: `=`, `!=`, `<>`, `<`, `>`, `<=`, `>=`, `<=>`, `LIKE`, `NOT LIKE`, `ILIKE`, `NOT ILIKE`, `IN`, `NOT IN`, `BETWEEN`, `NOT BETWEEN`, `IS`, `IS NOT`, `IS NULL`, `IS NOT NULL`, `EXISTS`, `NOT EXISTS`, `REGEXP`, `NOT REGEXP`, `RLIKE`, `GLOB`, `SIMILAR TO`, `NOT SIMILAR TO`, `~`, `~*`, `!~`, `!~*`, `@>`, `<@`, `&&`. Others throw a `DbException`. Array keys must be column names (`table.column` allowed). A field given to `Criteria` and a string condition are SQL: write them in code, never from request data. --- ## Joins ```php use Taphra\Criteria; use Taphra\SqlQuery; $rows = (new SqlQuery($conn)) ->select(['c.name', 'o.total']) ->from('customers', 'c') ->join('orders', 'o.customer_id = c.id', 'o') // INNER JOIN ->where(new Criteria('o.status', '=', 'paid')) ->fetch(true, false); $withOrders = (new SqlQuery($conn)) ->select(['c.name']) ->selectRaw('COUNT(o.id) AS orders') ->from('customers', 'c') ->leftJoin('orders', 'o.customer_id = c.id', 'o') ->groupBy(['c.id', 'c.name']) ->fetch(true, false); ``` Also `rightJoin()`, `fullOuterJoin()` (not MySQL) and `crossJoin($table, $alias)`. The join condition is SQL. --- ## Grouping, ordering, limits ```php use Taphra\SqlQuery; $rows = (new SqlQuery($conn)) ->select('customer_id') ->selectRaw('SUM(total) AS spent') ->from('orders') ->groupBy('customer_id') ->havingRaw('SUM(total) > ?', [50]) ->orderBy('spent', 'DESC') // a column or alias; 'a DESC, b' lists work too ->limit(10, 0) // limit, offset ->fetch(true, false); $byMonth = (new SqlQuery($conn)) ->selectRaw("substr(created_at, 1, 7) AS month, COUNT(*) AS n") ->from('orders') ->groupByRaw('substr(created_at, 1, 7)') ->orderByRaw('month') ->fetch(true, false); ``` `orderBy()` and `groupBy()` accept column names (and `table.column`, or a column position) only; `orderByRaw()` and `groupByRaw()` take expressions. `limit()` and `offset()` cast to integers. --- ## Raw SQL fragments `selectRaw()`, `whereRaw()`, `havingRaw()` and `orderByRaw()` take SQL with `?` placeholders and the values to bind: ```php use Taphra\SqlQuery; $rows = (new SqlQuery($conn)) ->selectRaw('name, salary * ? AS raised', [1.1]) ->from('employees') ->whereRaw('salary >= ? AND dept = ?', [90, 'eng']) ->orderByRaw('salary * ? DESC', [1]) ->fetch(true, false); ``` `getBindings()` returns the values of these raw fragments in placeholder order. --- ## Sub-queries ```php use Taphra\SqlQuery; $payers = (new SqlQuery($conn))->select('customer_id')->from('orders')->where(['status' => 'paid']); $rows = (new SqlQuery($conn))->select('*')->from('customers') ->whereSubquery('id', 'IN', $payers) // values of the sub-query are bound too ->fetch(true, false); $withOpen = (new SqlQuery($conn))->select('*')->from('customers', 'c') ->whereExists((new SqlQuery($conn))->select('id')->from('orders', 'o') ->whereRaw('o.customer_id = c.id')->where(['o.status' => 'new'])) ->fetch(true, false); $fromSub = (new SqlQuery($conn))->select('*') ->from((new SqlQuery($conn))->select(['customer_id', 'total'])->from('orders')->where(['status' => 'paid']), 'paid') ->fetch(true, false); ``` --- ## Common table expressions ```php use Taphra\SqlQuery; $recent = (new SqlQuery($conn))->select(['id', 'total'])->from('orders')->where(['created_at >=' => '2026-02-01']); $rows = (new SqlQuery($conn)) ->with('recent', $recent) ->select('*') ->from('recent') ->fetch(true, false); // Recursive: Eve and everyone below her. The CTE body is the anchor UNION ALL the recursive part. $anchor = (new SqlQuery($conn))->select(['id', 'name', 'manager_id'])->from('employees')->where(['id' => 1]); $recursive = (new SqlQuery($conn))->select(['e.id', 'e.name', 'e.manager_id']) ->from('employees', 'e')->join('tree', 'tree.id = e.manager_id'); $tree = (new SqlQuery($conn)) ->withRecursive('tree', $anchor->unionAll($recursive)) ->select('*')->from('tree') ->fetch(true, false); // Eve, Finn, Hal, Gus ``` --- ## Set operations ```php use Taphra\SqlQuery; $paid = (new SqlQuery($conn))->select('customer_id')->from('orders')->where(['status' => 'paid']); $new = (new SqlQuery($conn))->select('customer_id')->from('orders')->where(['status' => 'new']); $either = (new SqlQuery($conn))->select('customer_id')->from('orders')->where(['status' => 'paid']) ->union($new)->fetch(true, false); // UNION $both = (new SqlQuery($conn))->select('id')->from('customers') ->intersect((new SqlQuery($conn))->select('customer_id')->from('orders'))->fetch(true, false); // INTERSECT $never = (new SqlQuery($conn))->select('id')->from('customers') ->except((new SqlQuery($conn))->select('customer_id')->from('orders'))->fetch(true, false); // EXCEPT $all = (new SqlQuery($conn))->select('customer_id')->from('orders')->unionAll($paid)->fetch(true, false); ``` MySQL supports `INTERSECT` and `EXCEPT` from 8.0.31 (MariaDB from 10.3). --- ## Window functions ```php use Taphra\WindowSpec; use Taphra\SqlQuery; $rank = (new WindowSpec())->partitionBy('dept')->orderBy('salary', 'DESC'); $run = (new WindowSpec())->orderBy('id', 'ASC')->rowsBetween('UNBOUNDED PRECEDING', 'CURRENT ROW'); $rows = (new SqlQuery($conn)) ->select(['name', 'dept', 'salary']) ->selectWindow('RANK()', $rank, 'dept_rank') ->selectWindow('SUM(salary)', $run, 'running_total') ->selectWindow('AVG(salary)', new WindowSpec(), 'company_avg') // OVER () ->from('employees') ->fetch(true, false); ``` `WindowSpec`: `partitionBy(...$columns)`, `orderBy($column, $direction)`, `rowsBetween($start, $end)`, `rangeBetween($start, $end)`, `toSql()`. SQLite needs 3.25 or later, MySQL 8.0. --- ## INSERT, UPDATE, DELETE, upsert ```php use Taphra\Criteria; use Taphra\SqlQuery; (new SqlQuery($conn))->insert('customers', ['name' => 'Dee', 'email' => 'dee@example.com'])->execute(); (new SqlQuery($conn))->insert('orders', [ // several rows in one statement ['customer_id' => 4, 'total' => 5.00, 'status' => 'new', 'created_at' => '2026-03-01 10:00:00'], ['customer_id' => 4, 'total' => 6.00, 'status' => 'new', 'created_at' => '2026-03-02 10:00:00'], ])->execute(); // UPDATE and DELETE need a condition: a third argument or where(). (new SqlQuery($conn))->update('orders', ['status' => 'paid'])->where(new Criteria('customer_id', '=', 4))->execute(); (new SqlQuery($conn))->update('customers', ['active' => 0], new Criteria('email', '=', 'dee@example.com'))->execute(); (new SqlQuery($conn))->delete('orders')->where(['customer_id' => 4, 'total <' => 6])->execute(); // Insert, or update the given columns when the unique key already exists (new SqlQuery($conn)) ->upsert('customers', ['name' => 'Dee D.', 'email' => 'dee@example.com', 'active' => 1], ['email'], ['name', 'active']) ->execute(); // RETURNING (PostgreSQL, SQLite 3.35+): execute() returns the rows $created = (new SqlQuery($conn)) ->insert('customers', ['name' => 'Eli', 'email' => 'eli@example.com']) ->returning(['id', 'name']) ->execute(); // [['id' => 5, 'name' => 'Eli']] ``` An upsert is `INSERT ... ON DUPLICATE KEY UPDATE` on MySQL, `INSERT ... ON CONFLICT (...) DO UPDATE` on PostgreSQL and SQLite (`onConflictWhere()` adds a partial-index predicate), and `MERGE` on SQL Server. Column names in the data are quoted; a name containing a quote character is rejected. --- ## Row locking `lockForUpdate()` adds `FOR UPDATE` and `sharedLock()` adds `LOCK IN SHARE MODE` (MySQL) or `FOR SHARE` (PostgreSQL), inside a transaction. SQLite and SQL Server have no row locks; the query throws instead: ```php use Taphra\SqlQuery; try { (new SqlQuery($conn))->select('*')->from('orders')->where(['id' => 1])->lockForUpdate()->fetch(true, false); } catch (\Taphra\Db\DbException $e) { // SQLite does not support row-level locking } ``` --- ## Running SQL on the connection ```php $affected = $conn->execute('UPDATE customers SET active = ? WHERE id = ?', [1, 3]); $rows = $conn->query('SELECT name FROM customers WHERE active = ? ORDER BY id', true, false, [1]); $row = $conn->query('SELECT name FROM customers WHERE id = ?', false, false, [1]); $conn->beginTransaction(); $conn->execute('UPDATE orders SET status = ? WHERE id = ?', ['paid', 3]); $conn->commit(); // or $conn->rollback() ``` --- ## Inspecting a statement ```php use Taphra\SqlQuery; $q = (new SqlQuery($conn))->select('*')->from('orders')->where(['status' => 'paid'])->limit(5); $st = $q->toString(); // ['sqlWithParams' => 'SELECT * FROM orders ... = ? LIMIT 5', 'values' => ['paid']] $sql = $q->toSqlString(); // the same SQL with the values inlined (quoted by the driver), for logs $conn->quoteIdentifier('orders.status'); // `orders`.`status` here, "orders"."status" on PostgreSQL ``` `toSqlString()` output is for reading; run statements with `fetch()` or `execute()`, which bind the values. --- Source: https://taphra.dev/docs/authentication/ # Authentication This page covers who the user is: the `Auth` facade and its drivers, passwords, logging in with a session, protecting pages and API routes, remember-me cookies, JSON Web Tokens, policies, password reset and email verification tokens, and two-factor codes. The protections around them (CSRF, cookies, headers, encryption) are in [Security](security.md). Every PHP example below marked as runnable runs as written, in order, against SQLite. ## Contents - [The Auth facade](#the-auth-facade) - [Users and passwords](#users-and-passwords) - [Logging in with a session](#logging-in-with-a-session) - [Protecting pages and API routes](#protecting-pages-and-api-routes) - [Remember me](#remember-me) - [JSON Web Tokens](#json-web-tokens) - [Policies](#policies) - [Password reset and email verification](#password-reset-and-email-verification) - [Two-factor authentication](#two-factor-authentication) - [Sessions](#sessions) ## The Auth facade `Taphra\Auth` is a static facade over one driver. The default driver, `Taphra\Auth\SessionAuth`, keeps the user in the session and needs no setup. `Taphra\Auth\JwtAuth` reads a bearer token instead (see [JSON Web Tokens](#json-web-tokens)). | Method | Does | |---|---| | `Auth::login(array $user)` | stores the user (an array with at least `id`); SessionAuth gives the session a new ID | | `Auth::logout()` | forgets the user; SessionAuth gives the session a new ID, JwtAuth revokes the token | | `Auth::check(): bool`, `Auth::guest(): bool` | whether a user is logged in | | `Auth::user(?string $field = null)` | the stored array, one field of it, or null | | `Auth::id()` | `Auth::user('id')` | | `Auth::require(): array` | the user, or a `Taphra\Exceptions\UnauthorizedException` (401) | To configure the driver, set it once in `app/bootstrap.php`: ```php // app/bootstrap.php use Taphra\Auth; use Taphra\Auth\SessionAuth; Auth::setDriver(new SessionAuth([ 'session_key' => '_tphr_user', // where the user array lives in $_SESSION (default) 'remember_cookie' => '_tphr_remember', // remember-me cookie name (default) 'secure' => true, // remember-me cookie over HTTPS only; default: detect HTTPS ])); ``` Store only what you need on every request in the user array (id, name, role), not the password hash. ## Users and passwords The examples use this table and DataStore: ```php use Taphra\DatabaseConnection; use Taphra\SchemaBuilder; $schema = new SchemaBuilder(DatabaseConnection::load('app_master')); foreach (['remember_tokens', 'posts', 'users'] as $table) { $schema->dropIfExists($table); } $schema->create('users', function ($t) { $t->id(); $t->string('name', 100); $t->string('email')->unique(); $t->string('password'); $t->string('role', 20)->default('author'); }); ``` ```php // app/DataStores/UserDataStore.php namespace App\DataStores; class UserDataStore extends AppDataStore { public $objectName = 'users'; protected $fillable = ['name', 'email', 'password', 'role']; } ``` `Auth::hashPassword()` hashes with Argon2id when PHP supports it, otherwise bcrypt (`password_hash()`); it refuses a password containing a NUL byte, and with bcrypt one longer than 72 bytes (bcrypt ignores the rest), with an `Auth\UnusablePasswordException` whose message can be shown to the user. `Auth::setPasswordAlgorithm()` picks one explicitly. `Auth::verifyPassword()` checks a password against a hash in constant time; `Auth::needsRehash()` says when a stored hash should be replaced, for example after the cost or the algorithm changed: an existing bcrypt hash reports true once Argon2id is the default, so rehash it after a successful login. ```php use App\DataStores\UserDataStore; use Taphra\Auth; $alice = UserDataStore::create([ 'name' => 'Alice', 'email' => 'alice@example.com', 'password' => Auth::hashPassword('correct horse battery staple'), 'role' => 'admin', ]); var_dump(Auth::verifyPassword('correct horse battery staple', $alice['password'])); // bool(true) var_dump(Auth::verifyPassword('wrong', $alice['password'])); // bool(false) var_dump(Auth::needsRehash($alice['password'])); // bool(false) ``` ## Logging in with a session A login page is a form and an action that checks the password, counts failed attempts, and calls `Auth::login()`. The skeleton's `AppController` checks the CSRF token of every POST, so the form carries it. ```yaml GET: /login: login/show /account: account/index POST: /login: login/submit /logout: login/logout PUT: /posts/{id:\d+}: postEdit/update groups: api: prefix: /api middleware: [Taphra\Http\AuthMiddleware] routes: GET /me: me/show jwt: prefix: /jwt middleware: [App\Http\ApiJwtMiddleware] routes: GET /me: jwtMe/show ``` ```php

Sign in

csrf() ?> ``` ```php // app/Controllers/LoginController.php namespace App\Controllers; use App\DataStores\UserDataStore; use Taphra\Auth; use Taphra\RateLimiter; use Taphra\Request; class LoginController extends AppController { public function show(): void { $this->form('', ''); } public function submit(): void { $email = Request::str('email'); $limiter = RateLimiter::make('login', 5, 900); // 5 attempts per 15 minutes $key = Request::clientIP() . '|' . strtolower($email); // attempt() counts and checks in one step: parallel requests cannot // all pass the check before one of them is counted. if (!$limiter->attempt($key)) { http_response_code(429); $this->form($email, 'Too many attempts. Try again in ' . $limiter->availableIn($key) . ' seconds.'); return; } // An unknown email is checked against a dummy hash (null), so the // answer takes as long as for a real account. $user = UserDataStore::firstWhere(['email' => $email]); $password = (string) Request::input('password', ''); // not trimmed if (!Auth::verifyPassword($password, $user['password'] ?? null) || $user === null) { http_response_code(422); $this->form($email, 'These credentials do not match our records.'); return; } $limiter->clear($key); Auth::login($user->only(['id', 'name', 'email', 'role'])); $this->redirect('/account'); } public function logout(): void { Auth::logout(); $this->redirect('/login'); } private function form(string $email, string $error): void { $this->viewTitle = 'Sign in'; $this->email = $email; $this->error = $error; $this->render('show'); } } ``` `redirect()` sends the `Location` header and ends the request. The form, a failed attempt, and a post without the token: ```php use Taphra\Security; $page = docs_request('GET', '/login'); echo $page->getStatusCode(), ' ', str_contains((string) $page->getBody(), 'name="_csrf_token"') ? 'has a token' : 'no token', "\n"; // 200 has a token $token = Security::generateCsrfToken(); // the value the form carries $failed = docs_request('POST', '/login', ['email' => 'alice@example.com', 'password' => 'wrong', '_csrf_token' => $token]); echo $failed->getStatusCode(), "\n"; // 422 echo docs_request('POST', '/login', ['email' => 'alice@example.com', 'password' => 'wrong'])->getStatusCode(), "\n"; // 403 (no CSRF token) ``` On success the user array is in the session until logout: ```php use App\DataStores\UserDataStore; use Taphra\Auth; Auth::login(UserDataStore::firstWhere(['email' => 'alice@example.com'])->only(['id', 'name', 'email', 'role'])); var_dump(Auth::check()); // bool(true) echo Auth::user('name'), "\n"; // Alice echo Auth::id(), "\n"; // 1 ``` Count failed attempts per account and address, as above, so a password cannot be guessed at speed; `RateLimiter` counts in a fixed window (see [Security](security.md#rate-limiting)). ## Protecting pages and API routes For pages, check in `beforeAction()` and send guests to the login form: ```php // app/Controllers/AccountController.php namespace App\Controllers; use Taphra\Auth; class AccountController extends AppController { public function beforeAction() { parent::beforeAction(); // keeps the CSRF check if (Auth::guest()) { $this->redirect('/login'); } } public function index(): string { return 'Hello, ' . e(Auth::user('name')); } } ``` For APIs, put the routes in a group with `Taphra\Http\AuthMiddleware` (the `api` group in the routes file above). It answers a request without a logged-in user with `401` and a JSON body, and lets the others through. Route group middleware runs on both entries: the web front controller and the PSR-15 pipeline used by tests. ```php // app/Controllers/MeController.php namespace App\Controllers; use Taphra\Auth; use Taphra\RestController; class MeController extends RestController { public function show(): string { return $this->json(Auth::require()); } } ``` ```php use Taphra\Auth; echo docs_request('GET', '/api/me')->getBody(), "\n"; // {"id":1,"name":"Alice","email":"alice@example.com","role":"admin"} Auth::logout(); $guest = docs_request('GET', '/api/me'); echo $guest->getStatusCode(), ' ', $guest->getHeaderLine('WWW-Authenticate'), "\n"; // 401 Bearer realm="Taphra" echo $guest->getBody(), "\n"; // {"error":"Unauthorized","message":"Authentication required."} ``` `new AuthMiddleware(['/api/health'])` leaves the listed paths, and everything below them, open. A route bound to middleware is not reachable through its `/controller/action` convention URL either (that answers 404), so the middleware cannot be skipped. Outside a group, `Auth::require()` in an action does the same check: it throws `UnauthorizedException`, which the framework answers with 401. ## Remember me `Auth::loginWithRemember($user, int $days = 30, ?callable $store = null)` logs in and sets a long-lived `_tphr_remember` cookie (HttpOnly, SameSite=Lax) holding a random token. Store a hash of the token, never the token. On a later visit without a session, `Auth::resumeFromRemember(callable $userResolver, ?callable $rotateStore = null, int $days = 30)` looks the token up and logs the user in; with `$rotateStore` it replaces the token on every resume, which limits how long a stolen cookie works. `Auth::forgetRemember()` deletes the cookie. ```php use App\DataStores\UserDataStore; use Taphra\Auth; use Taphra\DatabaseConnection; use Taphra\SchemaBuilder; (new SchemaBuilder(DatabaseConnection::load('app_master')))->create('remember_tokens', function ($t) { $t->id(); $t->integer('user_id'); $t->string('token_hash', 64)->unique(); $t->dateTime('expires_at'); }); $tokens = DatabaseConnection::load('app_master'); // At login, when "remember me" is ticked: $user = UserDataStore::firstWhere(['email' => 'alice@example.com'])->only(['id', 'name', 'email', 'role']); $token = Auth::loginWithRemember($user, 30, function (string $token, array $user) use ($tokens) { $tokens->execute( 'INSERT INTO remember_tokens (user_id, token_hash, expires_at) VALUES (?, ?, ?)', [$user['id'], hash('sha256', $token), date('Y-m-d H:i:s', time() + 86400 * 30)] ); }); // A later request: no session, only the cookie. Auth::logout(); $_COOKIE['_tphr_remember'] = $token; $resumed = Auth::resumeFromRemember( function (string $token) use ($tokens): ?array { $row = $tokens->query('SELECT user_id FROM remember_tokens WHERE token_hash = ? AND expires_at > ?', false, false, [hash('sha256', $token), date('Y-m-d H:i:s')]); return $row ? UserDataStore::findById($row['user_id'])?->only(['id', 'name', 'email', 'role']) : null; }, function (string $new, string $old, array $user) use ($tokens) { $tokens->execute('UPDATE remember_tokens SET token_hash = ? WHERE token_hash = ?', [hash('sha256', $new), hash('sha256', $old)]); } ); var_dump($resumed, Auth::user('name')); // bool(true) string(5) "Alice" ``` Call `resumeFromRemember()` early in each request, for example at the top of `AppController::beforeAction()`. At logout call `Auth::forgetRemember()` with `Auth::logout()` and delete the stored hash. The cookie is `Secure` when the request itself is HTTPS (`$_SERVER['HTTPS']`); behind a proxy that ends TLS, pass `'secure' => true` to `SessionAuth`. ## JSON Web Tokens There are two ways to authenticate API requests with a bearer token. ### Jwt and JwtMiddleware (no extra package) `Taphra\Auth\Jwt` signs and checks HS256 tokens with PHP's own functions. The secret must be at least 32 bytes; a shorter one throws `InvalidArgumentException`, on encode and decode alike. Generate one with `php -r 'echo bin2hex(random_bytes(32)), "\n";'` and keep it in the environment. ```php use Taphra\Auth\Jwt; $secret = bin2hex(random_bytes(32)); // in an app: getenv('JWT_SECRET') putenv("JWT_SECRET=$secret"); $jwt = Jwt::encode(['sub' => 1, 'role' => 'admin'], $secret, 900); // iat and exp added; ttl 0 = no exp $claims = Jwt::decode($jwt, $secret); // RuntimeException: bad signature or expired; InvalidArgumentException: malformed echo $claims['sub'], ' ', $claims['exp'] - $claims['iat'], "\n"; // 1 900 try { Jwt::encode(['sub' => 1], 'too-short'); } catch (InvalidArgumentException $e) { echo $e->getMessage(), "\n"; // JWT secret must be at least 32 bytes long; got 9. } ``` `Taphra\Auth\JwtMiddleware(string $secret, array $exclude = [], string $attribute = 'jwt_payload')` checks the `Authorization: Bearer` header of every request it sees. A missing, malformed, badly signed or expired token gets `401` with an RFC 7807 body; a valid one continues with the claims in `JwtMiddleware::payload()` (null when no token was verified) and in the PSR-7 request attribute. Never read `$_REQUEST['_jwt']` for this: a client can send that parameter on a route without the middleware. Route groups create their middleware without arguments, so give the secret in a small subclass: ```php // app/Http/ApiJwtMiddleware.php namespace App\Http; use Taphra\Auth\JwtMiddleware; class ApiJwtMiddleware extends JwtMiddleware { public function __construct() { parent::__construct((string) getenv('JWT_SECRET')); } } ``` ```php // app/Controllers/JwtMeController.php namespace App\Controllers; use Taphra\Auth\JwtMiddleware; use Taphra\RestController; class JwtMeController extends RestController { public function show(): string { return $this->json(['user_id' => JwtMiddleware::payload()['sub'] ?? null]); } } ``` ```php echo docs_request('GET', '/jwt/me', [], ['Authorization' => "Bearer $jwt"])->getBody(), "\n"; // {"user_id":1} $denied = docs_request('GET', '/jwt/me'); echo $denied->getStatusCode(), ' ', $denied->getBody(), "\n"; // 401 {"type":"about:blank","title":"Unauthorized","status":401,"detail":"Authorization header missing or not a Bearer token."} ``` #### Access and refresh tokens Say what a token is for in its `token_use` claim when you issue it: `Jwt::ACCESS` (`"access"`) for the short-lived token that authenticates requests, `Jwt::REFRESH` (`"refresh"`) for the long-lived one that only gets a new access token. `JwtMiddleware` and the `JwtAuth` driver accept access tokens only (`Jwt::isAccessToken($claims)`): a refresh token, or any other `token_use`, gets `401`. A token issued without `token_use` still passes unless a `_type`, `typ` or `type` claim marks it as a refresh token, so tokens from `Jwt::encode(['sub' => 1], ...)` keep working; refresh tokens from controllers `make:auth` wrote before 1.0.0 (`"_type": "refresh"`) are refused. ```php use Taphra\Auth\Jwt; $access = Jwt::encode(['sub' => 1, 'token_use' => Jwt::ACCESS], $secret, 900); $refresh = Jwt::encode(['sub' => 1, 'token_use' => Jwt::REFRESH], $secret, 604800); echo docs_request('GET', '/jwt/me', [], ['Authorization' => "Bearer $access"])->getBody(), "\n"; // {"user_id":1} $refused = docs_request('GET', '/jwt/me', [], ['Authorization' => "Bearer $refresh"]); echo $refused->getStatusCode(), ' ', json_decode((string) $refused->getBody(), true)['detail'], "\n"; // 401 The token is not an access token. var_dump(Jwt::isRefreshToken(Jwt::decode($refresh, $secret))); // bool(true) ``` The refresh endpoint is the one place a refresh token works: leave it out of the middleware (list it in `$exclude`, or keep it outside the route group), decode the token yourself and check `Jwt::isRefreshToken($claims)` before issuing a new access token. `php taphra make:auth` writes such a controller. Issue the token from a login action that is not behind the middleware (or list its path in `$exclude`), after checking the password as in [Logging in with a session](#logging-in-with-a-session). ### The JwtAuth driver `Taphra\Auth\JwtAuth` makes `Auth::check()`, `Auth::user()` and policies work from the bearer token, adds a unique `jti` and `token_use: access` to every token it issues, refuses refresh tokens as `JwtMiddleware` does, and revokes tokens on logout. It needs `firebase/php-jwt` 7.2 or later (6.10 and later have the same API, but Composer's audit blocks the 6.x releases): ```bash composer require firebase/php-jwt:^7.2 ``` ```php // app/bootstrap.php use Taphra\Auth; use Taphra\Auth\JwtAuth; Auth::setDriver(new JwtAuth([ 'secret' => (string) getenv('JWT_SECRET'), // at least 32 bytes for HS* algorithms 'algo' => 'HS256', // default 'ttl' => 900, // seconds, default 3600 ])); ``` ```php // In the login action, after the password check: $token = Auth::issueToken($user->only(['id', 'role'])); // return it to the client // In later requests (Authorization: Bearer ): Auth::check(); // true for a valid, unexpired, unrevoked token Auth::user('role'); // claims, including jti and exp Auth::logout(); // revokes this token until it would have expired Auth::revokeToken(Auth::user('jti'), max(0, Auth::user('exp') - time())); // for example after a password change ``` Revoked token IDs live in the application cache. With several servers, use a shared cache backend (Redis) so a revocation applies everywhere. ## Policies A policy decides what a user may do with one kind of resource. Put it in `app/Policies/`, named after the resource: `PostPolicy` for `'Post'`. Each public method is an ability; it receives the current user (`Auth::user()`, null for a guest) and, when given, the resource. `before()` runs first: return `true` to allow everything, `false` to deny everything, or `null` to ask the ability method. ```php // app/Policies/PostPolicy.php namespace App\Policies; use Taphra\Auth\Policy; class PostPolicy extends Policy { public function before(mixed $user): ?bool { return ($user['role'] ?? null) === 'admin' ? true : null; } public function create(?array $user): bool { return $user !== null; } public function update(?array $user, array $post): bool { return $user !== null && $user['id'] === $post['user_id']; } } ``` ```php use Taphra\Auth; $post = ['id' => 10, 'user_id' => 2, 'title' => 'Not yours']; Auth::login(['id' => 2, 'name' => 'Bob', 'role' => 'author']); var_dump(Auth::can('update', 'Post', $post)); // bool(true): Bob owns it Auth::login(['id' => 3, 'name' => 'Carol', 'role' => 'author']); var_dump(Auth::can('update', 'Post', $post)); // bool(false) var_dump(Auth::cannot('update', 'Post', $post)); // bool(true) Auth::login(['id' => 1, 'name' => 'Alice', 'role' => 'admin']); var_dump(Auth::can('update', 'Post', $post)); // bool(true): before() lets admins through ``` In a controller, `$this->authorize('update', 'Post', $post)` throws `Taphra\Exceptions\ForbiddenException` when the answer is no (the framework answers 403), and `$this->can(...)` returns the boolean. An ability the policy does not define, or a policy that cannot be found, is a no. ```php // app/Controllers/PostEditController.php namespace App\Controllers; use Taphra\RestController; class PostEditController extends RestController { public function update(int $id): string { $post = ['id' => $id, 'user_id' => 2]; // in an app: PostDataStore::findById($id) $this->authorize('update', 'Post', $post); return $this->json(['updated' => $id]); } } ``` ```php use Taphra\Auth; Auth::login(['id' => 3, 'name' => 'Carol', 'role' => 'author']); echo docs_request('PUT', '/posts/10')->getStatusCode(), "\n"; // 403 Auth::login(['id' => 2, 'name' => 'Bob', 'role' => 'author']); echo docs_request('PUT', '/posts/10')->getBody(), "\n"; // {"updated":10} ``` `PolicyGate::register('Post', PostPolicy::class)` maps a resource to a policy explicitly, and `PolicyGate::setUserResolver(fn () => ...)` changes where the user comes from, for example `JwtMiddleware::payload()` with `JwtMiddleware` (both in `Taphra\Auth\PolicyGate`). ## Password reset and email verification Both work with single-purpose tokens kept in the application cache (hashed, per email address), so they need no table. Send the token in a link; check it when the link is opened; invalidate it once used. ```php use Taphra\Auth; $reset = Auth::createPasswordResetToken('alice@example.com'); // valid 1 hour (ttl argument) var_dump(Auth::verifyPasswordResetToken('alice@example.com', $reset)); // bool(true) var_dump(Auth::verifyPasswordResetToken('alice@example.com', 'guess')); // bool(false) Auth::invalidatePasswordResetToken('alice@example.com'); // after the new password is saved var_dump(Auth::verifyPasswordResetToken('alice@example.com', $reset)); // bool(false) $verify = Auth::createVerificationToken('bob@example.com'); // valid 24 hours var_dump(Auth::emailVerificationPending('bob@example.com')); // bool(true) var_dump(Auth::verifyEmailToken('bob@example.com', $verify)); // bool(true) Auth::invalidateVerificationToken('bob@example.com'); ``` Limit how often the endpoints that send these emails can be called (per address and per IP), so they cannot be used to flood an inbox. ## Two-factor authentication Time-based one-time passwords (TOTP, RFC 6238) work with authenticator apps. Generate a secret when the user turns two-factor on, show it as a QR code of the provisioning URI, and ask for a code at each login after the password. ```php use Taphra\Auth; use Taphra\Auth\Totp; $secret = Auth::generateTotpSecret(); // Base32, 160 bits: store it encrypted echo Auth::totpProvisioningUri($secret, 'alice@example.com', 'MyApp'), "\n"; // otpauth://totp/MyApp%3Aalice%40example.com?secret=...&issuer=MyApp&algorithm=SHA1&digits=6&period=30 $code = Totp::generate($secret); // what the user's app shows right now var_dump(Auth::verifyTotp($secret, $code)); // bool(true) var_dump(Auth::verifyTotp($secret, $code)); // bool(false): a code works once ``` `verifyTotp()` accepts the previous and next 30-second step for clock drift (`$window = 1`), and claims each accepted step in the application cache with an atomic add, so a code cannot be used twice, even by two requests at the same moment. A plain PSR-16 cache handed to `Auth::setCacheDriver()` has no atomic add: then the check is a read followed by a write, and two simultaneous requests could both pass. It fails closed: when the cache cannot be read or written, it returns false. Limit wrong codes per account with `Totp::setAttemptLimiter(RateLimiter::make('totp', 5, 300))`; while the limit is reached, every code is refused. Backup codes let a user in when the phone is lost. Show the plain codes once, store only their hashes, and mark a code used after it matches: ```php use Taphra\Auth; $codes = Auth::generateBackupCodes(); // 10 codes $hashes = Auth::hashBackupCodes($codes); // store these $matched = ''; var_dump(Auth::verifyBackupCode($codes[3], $hashes, $matched)); // bool(true) var_dump($matched === $hashes[3]); // bool(true): mark this hash used ``` Encrypt the TOTP secret at rest with `Crypt::encrypt()` (see [Security](security.md#encryption)); someone who reads a plain secret can generate valid codes. ## Sessions `Taphra\Session` wraps PHP sessions; values live under one key of `$_SESSION`, so they do not collide with other libraries. ```php use Taphra\Session; Session::start(); // also started on demand by Auth, CSRF tokens and flash data Session::set('cart_id', 42); Session::get('cart_id'); // 42 Session::get('missing', 'none'); // 'none' Session::exists('cart_id'); // true Session::delete('cart_id'); Session::regenerateId(); // new ID, same data (Auth::login() does this for you) Session::destroy(); ``` Settings in `app/Config/app.yml`: ```yaml all: session: method: file # file (PHP's handler) or database # config: app_master # with method: database, the connection; the table is created on first use # table: sessions timeout: 7200 # seconds; else session.cookie_lifetime, then session.gc_maxlifetime from php.ini # cookie: # overrides for the session cookie # domain: .example.com # samesite: Strict ``` The session cookie is HttpOnly, SameSite=Lax and, on HTTPS, Secure; PHP runs in strict mode with cookies only. The details are in [Security](security.md#sessions-and-cookies). --- Source: https://taphra.dev/docs/security/ # Security This page lists what Taphra protects by default, what each default does, and what you still set up yourself, then ends with a checklist for production. Logging users in, tokens and policies are in [Authentication](authentication.md). Every PHP example below marked as runnable runs as written, in order. ## Contents - [Environments and error pages](#environments-and-error-pages) - [CSRF](#csrf) - [Sessions and cookies](#sessions-and-cookies) - [Security headers](#security-headers) - [Proxies, client IPs and URLs](#proxies-client-ips-and-urls) - [Escaping output](#escaping-output) - [SQL](#sql) - [Encryption](#encryption) - [Rate limiting](#rate-limiting) - [Queues, MCP and the AI builder](#queues-mcp-and-the-ai-builder) - [Logs](#logs) - [Production checklist](#production-checklist) ## Environments and error pages The mode comes from the `APP_ENV` environment variable, read in `app/bootstrap.php`: | `APP_ENV` | Mode | |---|---| | `dev`, `development`, `local` | development | | `stg`, `stage`, `staging` | staging | | anything else, or unset | production | `IS_PRODUCTION=1` forces production whatever `APP_ENV` says. A server that forgets to set `APP_ENV` therefore runs in production mode. `php taphra serve` sets `APP_ENV=dev` for the development server it starts. The debug error page (Whoops, with the stack trace, request data and queries) is registered in development only. In staging and production an uncaught exception is logged and answered with the right status (403, 404, 405, 500) and the app's `error404.tpl.php` or `error500.tpl.php` view, or a JSON body without details for clients that ask for JSON (see [REST APIs](rest-apis.md#errors)). `display_errors` comes from `app.yml` (`0` in the skeleton's `prod` section). ```php foreach (['dev', 'local', 'staging', 'production', 'test', ''] as $env) { echo str_pad("'$env'", 13), modeFromEnvironment($env, false), "\n"; } // 'dev' dev // 'local' dev // 'staging' stg // 'production' prod // 'test' prod // '' prod ``` ## CSRF The skeleton's `AppController`, the base of its HTML controllers, sets `protected $autoVerifyCsrf = true;`. Every request that is not GET, HEAD or OPTIONS must then carry the session's CSRF token, in the `_csrf_token` form field or the `X-CSRF-Token` header; otherwise the action does not run and the request ends with `403 Forbidden`. Put the token in every form: ```php
csrf() ?> ... ``` `$html->formOpen('/notes')` from the [HTML helper](views.md) adds it too. For JavaScript requests (fetch, HTMX), print the token once in the layout, for example in a `` tag filled from `Taphra\Security::generateCsrfToken()`, and send it as the `X-CSRF-Token` header. The token is 64 hex characters, one per session, compared in constant time. ```yaml POST: /notes: note/store ``` ```php // app/Controllers/NoteController.php namespace App\Controllers; class NoteController extends AppController { public function store(): string { return 'saved'; } } ``` ```php use Taphra\Security; $token = Security::generateCsrfToken(); // what $this->csrf() put in the form echo docs_request('POST', '/notes')->getStatusCode(), "\n"; // 403 echo docs_request('POST', '/notes', ['_csrf_token' => 'forged'])->getStatusCode(), "\n"; // 403 echo docs_request('POST', '/notes', ['_csrf_token' => $token])->getBody(), "\n"; // saved ``` The `X-CSRF-Token` header works the same way. Bind each state-changing action to POST, PUT, PATCH or DELETE in `routes.yml` (see [Routing](routing.md)); a GET to it then gets 405, so a link or an image cannot trigger it. Controllers that extend `RestController` directly do not check the token: an API that authenticates every request with an `Authorization` header is not exposed to CSRF, because browsers do not add that header on their own. An API that relies on the session cookie must check a token, either by setting `protected $autoVerifyCsrf = true;` on its controllers or with the double-submit cookie for single-page apps: ```php use Taphra\Security; // When the page loads: a random token in a cookie that JavaScript can read // (XSRF-TOKEN, SameSite=Strict, not HttpOnly). Security::setCsrfCookie(); // On each state-changing request: the client copies the cookie into the X-XSRF-Token header. if (!Security::validateCsrfHeader()) { return $this->apiError(403, 'CSRF token mismatch.'); } ``` For a form with its own token, pass the same id to both sides: `$this->csrf('delete-account')` in the view and `$this->verifyCsrf('delete-account')` in the action (the automatic check uses the default id). ## Sessions and cookies Sessions start on demand (a login, a CSRF token, flash data), with these settings: | Setting | Value | |---|---| | `HttpOnly` | on: scripts cannot read the session cookie | | `SameSite` | `Lax`: the cookie is not sent on cross-site POSTs | | `Secure` | on when the request is HTTPS, including HTTPS ended at a [trusted proxy](#proxies-client-ips-and-urls) | | `session.use_strict_mode` | on: a session ID the server did not issue is replaced | | `session.use_only_cookies` | on: no session IDs in URLs | | lifetime | `app.session.timeout` seconds, else PHP's `session.cookie_lifetime`, then `session.gc_maxlifetime` | `Auth::login()` and `Auth::logout()` give the session a new ID, so an ID seen before login is useless after it. Override the cookie values under `app.session.cookie` (`lifetime`, `path`, `domain`, `secure`, `httponly`, `samesite`) in `app.yml`. The remember-me cookie is described in [Authentication](authentication.md#remember-me). `Taphra\Cookie::set($name, $value, $expiry = 0, ...)` sets your own cookies HttpOnly and SameSite=Lax by default, but not Secure: call `Cookie::configSecure(true)` once in `app/bootstrap.php` for an HTTPS site, or pass `$secure` per cookie. ## Security headers Every response of the web front controller carries: | Header | Value | |---|---| | `X-Content-Type-Options` | `nosniff` | | `X-Frame-Options` | `SAMEORIGIN` | | `Referrer-Policy` | `strict-origin-when-cross-origin` | | `X-XSS-Protection` | `0` (turns off the old browser filter, which caused leaks) | | `Strict-Transport-Security` | `max-age=31536000`, on HTTPS requests only | No `Content-Security-Policy` is sent by default, because it would block the inline styles and scripts many existing pages use. Add one, change a value, or remove a header with `~` under `security_headers` in `app.yml`: ```yaml prod: security_headers: Content-Security-Policy: "default-src 'self'" X-Frame-Options: DENY X-XSS-Protection: ~ ``` For inline scripts under a CSP, `Taphra\Security::nonce()` returns one random nonce per request, for both the header (`script-src 'nonce-...'`) and the `

'), "\n"; //

Hi there

``` [Views and helpers](views.md) has the details. ## SQL Values are always bound as parameters, column names and operators are checked, and SQL text goes in only through the methods that say so (`whereRaw()` and the other `*Raw()` methods, string conditions, the connection's `query()`). `$fillable` and `$guarded` limit mass assignment. See [Database: input safety](database.md#input-safety). ## Encryption `Taphra\Crypt` encrypts with libsodium (XSalsa20-Poly1305, a fresh random salt and nonce per message). The key must be at least 32 bytes; a shorter one throws `InvalidArgumentException`. `decrypt()` returns `false` for a wrong key or changed data, never partial plaintext. ```php use Taphra\Crypt; $key = bin2hex(random_bytes(32)); // in an app: from the environment $token = Crypt::encrypt('JBSWY3DPEHPK3PXP', $key); echo Crypt::decrypt($token, $key), "\n"; // JBSWY3DPEHPK3PXP var_dump(Crypt::decrypt($token, bin2hex(random_bytes(32)))); // bool(false) try { Crypt::encrypt('x', 'short key'); } catch (InvalidArgumentException $e) { echo "refused: key too short\n"; } // For a secret a person types, the passphrase API derives the key with Argon2id: $sealed = Crypt::encryptWithPassphrase('notes', 'correct horse battery staple'); echo Crypt::decryptWithPassphrase($sealed, 'correct horse battery staple'), "\n"; // notes ``` The two pairs do not read each other's output. `php taphra key:generate` writes a random `APP_SECRET_KEY` to `.env`. Taphra loads `.env` at boot, and a variable already set in the process environment wins; in production, set the variables in the server's environment (PHP-FPM pool, systemd unit, container) rather than shipping a `.env` file. The package README, [packages/crypt/README.md](../packages/crypt/README.md), lists the exact format. ## Rate limiting `Taphra\RateLimiter` counts hits per key in a fixed window: the first hit opens a window of `$decaySeconds`, and the count starts again when it has passed. It stores the counts in the application cache (Redis when configured, else files). ```php use Taphra\RateLimiter; $limiter = RateLimiter::make('docs-api', 3, 60); // 3 hits per 60 seconds $key = '203.0.113.7'; // in an app: Request::clientIP() or a user id // attempt() counts the hit and checks the limit in one step, so parallel // requests cannot all pass before one of them is counted. for ($i = 1; $i <= 4; $i++) { if (!$limiter->attempt($key)) { echo "hit $i: refused, retry in ", $limiter->availableIn($key) > 0 ? 'under a minute' : 'now', "\n"; continue; } echo "hit $i: allowed, ", $limiter->remaining($key), " left\n"; } // hit 1: allowed, 2 left // hit 2: allowed, 1 left // hit 3: allowed, 0 left // hit 4: refused, retry in under a minute $limiter->clear($key); ``` `Taphra\Http\RateLimitMiddleware(RateLimiter::cacher(), $maxRequests, $windowSeconds)` applies one limit to every request through a PSR-15 pipeline and answers `429` with a `Retry-After` header. It counts per `Request::clientIP()`: behind a proxy listed in `trusted_proxies` each client gets its own limit; without the list every client shares the proxy's address. ## Queues, MCP and the AI builder - **Queue workers** run only jobs whose payload names a class implementing `Taphra\Queue\JobInterface` and one of its static methods; a payload naming any other class or function is refused. See [Queues](queues.md). - **MCP over HTTP** refuses every request (401) until you set a token of at least 32 bytes (the `TAPHRA_MCP_TOKEN` environment variable or `mcp.token` in `ai.yml`) or override `authorizeMcp()`; it refuses browser origins other than loopback and `mcp.allowed_origins` (403) and requires JSON. See [MCP server](mcp.md). - **The AI builder** (`ai:build`, `ai:fix`) asks before every file write (including the files `make:*` generators create) and before every command outside a fixed allow-list, never runs a shell, and keeps a receipt so `ai:rollback` can undo a session. See [AI builder](ai-builder.md). ## Logs Outside development, only notices, warnings and errors are written (`app.logging.level` changes the threshold); `logging.method: null` discards logs. The opt-in request log for `php taphra debug:request` (`logging.log_requests`) is never written in production, and it writes cookies, `Authorization`, session ids, token, secret, key, password, one-time code, PIN and CSRF headers and fields, bodies it cannot parse and token-like path segments as `[redacted]`. Logs can still hold user input and exception messages: keep `app/tmp/` out of the web root (the document root is `app/Static/`) and readable by the application user only. ## Production checklist - [ ] `APP_ENV=prod` (or simply not set to a development value) on every web server, worker and cron job. - [ ] `display_errors: 0` in the `prod` section of `app.yml` (the skeleton sets it). - [ ] `base_url` set in `prod`, so `url()` never uses the `Host` header. - [ ] `trusted_proxies` set when a load balancer or proxy is in front, and only then. - [ ] HTTPS everywhere; HSTS and the `Secure` cookie flag follow automatically. Call `Cookie::configSecure(true)` if you set your own cookies. - [ ] A `Content-Security-Policy` under `security_headers`, once your pages work with it. - [ ] Secrets (database password, `JWT_SECRET` of at least 32 bytes, `APP_SECRET_KEY`, AI and payment keys) come from the environment, not from files in the repository. - [ ] Every HTML controller extends `AppController` (CSRF on); every form prints `$this->csrf()`; every state-changing route is bound to POST, PUT, PATCH or DELETE. - [ ] APIs authenticate with a token (`AuthMiddleware` or a JWT middleware in a route group), or check CSRF when they use the session cookie. - [ ] Login, password reset and verification endpoints are rate limited; two-factor secrets are encrypted at rest. - [ ] DataStores declare `$fillable` (or `$guarded`); raw SQL methods never receive request data as SQL. - [ ] A shared cache (Redis) when several servers share sessions, rate limits, TOTP replay protection or JWT revocation. - [ ] The web server's document root is `app/Static/`; `app/tmp/` is writable by PHP and not served. - [ ] MCP over HTTP has a token; queue workers run as an unprivileged user. - [ ] After changing YAML configuration on a production server, run `php taphra cache:clear` (production keeps the parsed configuration cached), then `php taphra optimize` if you use it. See [Deployment](deployment.md). --- Source: https://taphra.dev/docs/ai/ # AI Taphra's AI layer talks to Anthropic, OpenAI, OpenAI-compatible servers and Ollama through one interface: completions, token streaming, structured output, tool use with an agent loop, conversations, prompt templates and embeddings. It lives in the bundled `taphra/ai` package (`Taphra\Ai`). This page covers it inside an app; [the package README](../packages/ai/README.md) covers using it without the framework. Every PHP example below runs as written, in order, with the network replaced by recorded provider responses (see [Testing](#testing)). ## Contents - [Configuration](#configuration) - [A first call](#a-first-call) - [Providers](#providers) - [Streaming](#streaming) - [Structured output](#structured-output) - [Tools and agents](#tools-and-agents) - [Usage and prompt caching](#usage-and-prompt-caching) - [Conversations](#conversations) - [Prompt templates](#prompt-templates) - [Embeddings](#embeddings) - [Fallback and caching](#fallback-and-caching) - [Errors](#errors) - [Logging](#logging) - [Testing](#testing) ## Configuration Providers are configured in `app/Config/ai.yml`: ```yaml default_provider: anthropic providers: anthropic: api_key: "${ANTHROPIC_API_KEY}" model: claude-opus-5-5 max_tokens: 4096 openai: api_key: "${OPENAI_API_KEY}" model: gpt-5.2 ollama: base_url: http://localhost:11434 model: llama3 vllm: # an OpenAI-compatible server, see below base_url: http://localhost:8000/v1 api_key: "${VLLM_API_KEY}" model: qwen3 ``` `${NAME}` placeholders are replaced with the environment variable of that name each time a value is read, so keys stay out of the file and out of the config cache. Taphra does not read a `.env` file at runtime: set the variables in your shell, your web server or PHP-FPM pool, or your container. Like other config files, `ai.yml` can be split into `all:`, `dev:`, `stg:` and `prod:` sections (see [configuration](configuration.md)). Provider keys, all optional except the API key of a hosted provider: | Provider | Default model | Keys | |---|---|---| | `anthropic` | `claude-opus-5-5` | `api_key`, `base_url`, `model`, `max_tokens` (default 16000), `temperature`, `top_p`, `top_k`, `thinking`, `effort`, `betas`, `api_version`, `structured_output`, `max_continuations`, `voyage_api_key` | | `openai` | `gpt-4o` | `api_key`, `base_url`, `model`, `max_tokens` (default 4096), `temperature`, `top_p`, `effort`, `strict`, `store`, `api`, `reasoning_model` | | `ollama` | `llama3` | `base_url` (default `http://localhost:11434`), `model`, `max_tokens` (default 4096), `temperature`, `think`, `keep_alive` | Every provider also takes `timeout` (seconds, default 120) and `stream_timeout` (default 600). Most keys can be overridden per call in the `$options` array of `complete()` and `stream()`. Other top-level settings: | Key | Default | Meaning | |---|---|---| | `agent.max_iterations` | 10 | Model calls an agent run may make | | `agent.timeout_seconds` | 120 | Request timeout when a provider sets no `timeout` | | `rate_limiting.retry_attempts` | 3 | Attempts for a request answered with HTTP 429 | | `rate_limiting.retry_base_delay_ms` | 500 | First retry delay, doubled for each later attempt | | `logging.enabled` | true | Write a line per request to `app/tmp/Log/ai.log`: usage or error, no prompts (see [Logging](#logging)) | | `logging.payloads` | false | Also write each request and answer (the prompts and replies) to that log | | `logging.redact_fields` | `[api_key, authorization]` | Fields replaced with `[REDACTED]` in logged requests and answers | ## A first call `AI::complete()` sends a list of messages to the default provider and returns the answer: ```php use Taphra\Ai\AI; $reply = AI::complete([ ['role' => 'system', 'content' => 'Answer in one sentence.'], ['role' => 'user', 'content' => 'What is a DataStore in Taphra?'], ]); echo $reply['content'], "\n"; echo $reply['stop_reason'], ', ', $reply['usage']['output_tokens'], " output tokens\n"; ``` Every provider returns the same array: | Key | Value | |---|---| | `content` | The text answer | | `role` | `assistant` | | `tool_calls` | Tool calls the model made: `[['id' => ..., 'name' => ..., 'input' => [...]], ...]` | | `stop_reason` | The provider's stop reason (`end_turn`, `stop`, `tool_use`, `max_tokens`, ...) | | `usage` | Token counts, see [Usage](#usage-and-prompt-caching) | | `thinking` | The model's reasoning text, when the provider returns one | | `parsed` | The decoded answer, when an output schema is set | | `native` | Anthropic and the OpenAI Responses API: the provider's own copy of the turn, sent back unchanged in tool loops | | `raw` | The provider's response as decoded JSON | Messages use one provider-neutral format: `system`, `user` and `assistant` roles with string content, plus `tool` messages for tool results. A user message can also carry a list of blocks, such as `['type' => 'text', 'text' => ...]` and `['type' => 'image', 'url' => ...]` or `['type' => 'image', 'base64' => ..., 'mime' => 'image/png']`. Each provider converts the list to its own wire format, so a history built with one provider can be sent to another. Ollama takes images as base64 only. ## Providers `AI::provider()` returns the default provider and `AI::provider('openai')` a named one; each is built once and kept for the life of the PHP process. The second argument of `complete()` overrides settings for one call: ```php use Taphra\Ai\AI; $reply = AI::provider('openai')->complete( [['role' => 'user', 'content' => 'Name three PHP array functions.']], ['max_tokens' => 300, 'effort' => 'low'], ); echo $reply['content'], "\n"; ``` Settings a model does not accept are left out of the request: - **Anthropic.** `temperature`, `top_p` and `top_k` are sent only to Anthropic models up to version 4.6; later models reject them. `effort` (`low`, `medium`, `high`, `xhigh`, `max`) is sent as `output_config.effort`. `thinking`, for example `['type' => 'adaptive']`, is sent as written; `betas` is a list of `anthropic-beta` values. - **OpenAI.** Reasoning models (the o-series and GPT-5 and later) are called through the Responses API (`/v1/responses`) with `max_output_tokens` and the reasoning effort, and without sampling settings. Earlier models such as `gpt-4o` use Chat Completions (`/v1/chat/completions`) with `max_tokens`, `temperature` and `top_p`. Force one API with `'api' => 'responses'` or `'api' => 'chat'`; for a model id the provider does not recognise, set `'reasoning_model' => true` or `false`. - **Ollama.** Runs local models over `/api/chat`. `think` and `keep_alive` are passed through. ### OpenAI-compatible servers `AI::provider()` knows the names `anthropic`, `openai` and `ollama`. For a server that implements the OpenAI Chat Completions API (vLLM, LM Studio, a hosted vendor), either point the `openai` section's `base_url` at it, or give it its own section and build the provider from it. Any `base_url` other than `api.openai.com` uses Chat Completions: ```php use Taphra\Ai\AiConfig; use Taphra\Ai\OpenAiProvider; $local = new OpenAiProvider(AiConfig::provider('vllm')); // providers.vllm in ai.yml echo $local->complete([['role' => 'user', 'content' => 'Ping?']])['content'], "\n"; ``` ## Streaming `stream()` returns a generator that yields the text as the provider sends it: Server-Sent Events for Anthropic and OpenAI, NDJSON for Ollama. The same loop works for each provider: ```php use Taphra\Ai\AI; foreach (['anthropic', 'openai', 'ollama'] as $name) { echo $name, ': '; foreach (AI::provider($name)->stream([['role' => 'user', 'content' => 'Say hello.']]) as $chunk) { echo $chunk; } echo "\n"; } ``` `stream()` yields text only; use `complete()` when you need tool calls, usage or structured output. An error event in the stream throws an `AiException`. ### Streaming to the browser A controller's protected `sse()` helper sends a generator (or a closure that returns one) as `text/event-stream`: one `data:` event per chunk, a chunk with line breaks split over several `data:` lines, and a final `data: [DONE]`. It turns off output buffering, flushes after each chunk, stops when the client disconnects, and ends the request when the stream is done. ```php // app/Controllers/ChatController.php namespace App\Controllers; use Taphra\Ai\AI; use Taphra\Request; class ChatController extends AppController { public function stream(): void { $question = Request::str('q'); $this->sse(AI::stream([['role' => 'user', 'content' => $question]])); } } ``` `GET /chat/stream?q=hello` then answers: ``` data: Hello data: there data: friend data: [DONE] ``` and the browser reads it with `EventSource`, which joins the `data:` lines of one event with a line break: ```js const source = new EventSource('/chat/stream?q=' + encodeURIComponent(question)); source.onmessage = (event) => { if (event.data === '[DONE]') { source.close(); return; } output.textContent += event.data; }; ``` See [routing and controllers](routing.md) for routes and the other response helpers. ## Structured output `StructuredOutput` asks for an answer that matches a JSON Schema, decodes it and checks it against the schema: ```php use Taphra\Ai\AI; use Taphra\Ai\StructuredOutput; $invoice = StructuredOutput::from(AI::provider()) ->schema([ 'type' => 'object', 'properties' => [ 'customer' => ['type' => 'string'], 'total' => ['type' => 'number'], 'paid' => ['type' => 'boolean'], ], 'required' => ['customer', 'total', 'paid'], ]) ->extract([['role' => 'user', 'content' => 'Invoice for Ada Lovelace, 120.50 EUR, settled on 3 May.']]); echo json_encode($invoice), "\n"; // {"customer":"Ada Lovelace","total":120.5,"paid":true} ``` How each provider asks for it: | Provider | Request | |---|---| | Anthropic | `output_config.format` with the schema (objects closed with `additionalProperties: false`), for Anthropic models from 4.1 on. Earlier models get the schema as a tool they must call; force either with `structured_output: output_format` or `tool`. | | OpenAI | `response_format` (Chat Completions) or `text.format` (Responses) of type `json_schema`. Strict mode is on when the schema meets its rules; set `strict: true` or `false` to choose. | | Ollama | The schema as `format`, with `temperature` 0 unless you set one | The answer is always checked here too. When the model declines, the answer is cut at the token limit, it is not JSON, or it does not match, `extract()` throws `AiStructuredOutputException`: ```php use Taphra\Ai\AI; use Taphra\Ai\AiStructuredOutputException; use Taphra\Ai\StructuredOutput; try { StructuredOutput::from(AI::provider()) ->schema(['type' => 'object', 'properties' => ['age' => ['type' => 'integer']], 'required' => ['age']]) ->extract([['role' => 'user', 'content' => 'How old is the Eiffel Tower?']]); } catch (AiStructuredOutputException $e) { echo $e->getMessage(), "\n"; } ``` `withOutputSchema($schema)` does the same on any provider and puts the decoded answer in `$reply['parsed']`. ## Tools and agents A tool is a class your code runs when the model asks for it. `php taphra make:tool Weather` writes `app/AiTools/WeatherTool.php`; its `name()` is the snake_case form of the class name (`weather`, `web_search`): ```php 'object', 'properties' => ['city' => ['type' => 'string', 'description' => 'City name']], 'required' => ['city'], ]; } public function execute(array $params) { $city = trim((string) ($params['city'] ?? '')); if ($city === '') { throw new \InvalidArgumentException('city is required'); } return ['city' => $city, 'temp_c' => 18, 'sky' => 'cloudy']; } } ``` `AgentLoop` sends the messages with the tools, runs each tool the model calls, sends the results back, and repeats until the model answers without calling a tool: ```php use App\AiTools\WeatherTool; use Taphra\Ai\AI; $agent = AI::agent() // the default provider; AI::agent('openai') for another ->registerTool(new WeatherTool()) ->maxIterations(5) ->onToolCall(function (string $name, array $params, string $result): void { echo "called $name(", json_encode($params), ")\n"; }); $answer = $agent->run('Should I take an umbrella in Paris today?'); echo $answer['content'], "\n"; ``` What the loop does: - The tool's return value is sent to the model as JSON (a string as it is). An exception in `execute()`, or a tool name the model made up, goes back to the model as an error result, so it can correct itself. - The loop does not check the model's arguments against `inputSchema()`. Validate them in `execute()`, as above, and treat them like any other user input. - When the limit of model calls is reached, `run()` throws `AiMaxIterationsException`. - `history()` returns the conversation so far, in the provider-neutral format, and the next `run()` continues it; `reset()` clears it. - `useRegisteredTools()` loads `app/AiTools/*.php` and registers every concrete `AiTool` class declared there (or in the `App\AiTools` namespace) whose constructor takes no required arguments. Register any other tool with `registerTool()`. The history keeps each assistant turn in the provider's own form as well (`native`): Anthropic thinking blocks with their signatures, and OpenAI reasoning items, which those APIs require back unchanged during tool use. Another provider reading the same history uses the plain `content` and `tool_calls`. Without the loop, `withTools([...])` returns a provider that offers the tools, and the calls arrive in `$reply['tool_calls']` for you to handle. ### Thinking Ask Anthropic for extended thinking with the `thinking` option (or key); the reasoning text arrives in `thinking`, next to the answer. OpenAI reasoning summaries and Ollama's `think` output use the same key. ```php use Taphra\Ai\AI; $reply = AI::complete( [['role' => 'user', 'content' => 'Is 1001 a prime number?']], ['thinking' => ['type' => 'adaptive'], 'effort' => 'high'], ); echo $reply['thinking'], "\n", $reply['content'], "\n"; ``` ### Server tools A server tool runs at the provider, such as Anthropic's or OpenAI's web search. Pass its raw definition; it is sent to the provider as written: ```php use Taphra\Ai\AI; $reply = AI::agent() ->addProviderTool(['type' => 'web_search_20260209', 'name' => 'web_search', 'max_uses' => 3]) ->run('What is the latest PHP release?'); echo $reply['content'], "\n"; echo json_encode($reply['usage']['server_tool_use']), "\n"; // {"web_search_requests":1} ``` On the OpenAI Responses API the definition is `['type' => 'web_search']`. When Anthropic pauses a long server-tool turn (`pause_turn`), the provider resumes it, up to `max_continuations` times (default 5), and adds up the usage. ## Usage and prompt caching `$reply['usage']` has the same keys for every provider: | Key | Meaning | |---|---| | `input_tokens` | Input tokens as the provider reports them (Anthropic counts only uncached input here; OpenAI and Ollama count all input) | | `output_tokens` | Output tokens, reasoning included | | `cache_read_tokens` | Input tokens served from the prompt cache | | `cache_write_tokens` | Input tokens written to the prompt cache | | `uncached_input_tokens` | Input tokens billed at the base input rate | | `total_input_tokens` | Uncached plus cache read plus cache write | | `reasoning_tokens` | The part of `output_tokens` spent on reasoning, when reported | | `server_tool_use` | Server tool calls by kind, for example `['web_search_requests' => 2]` | To price a call, multiply `uncached_input_tokens`, `cache_read_tokens`, `cache_write_tokens` and `output_tokens` by their rates and add the server tool calls. With Anthropic, a text block can carry `cache_control` to mark a long, repeated prefix for the prompt cache; extra keys on text blocks are sent as written: ```php use Taphra\Ai\AI; $manual = str_repeat('Section 4.2: refunds are issued within 14 days. ', 200); $reply = AI::complete([ ['role' => 'user', 'content' => [ ['type' => 'text', 'text' => $manual, 'cache_control' => ['type' => 'ephemeral']], ['type' => 'text', 'text' => 'How long do refunds take?'], ]], ]); printf("uncached %d, cache read %d, total input %d\n", $reply['usage']['uncached_input_tokens'], $reply['usage']['cache_read_tokens'], $reply['usage']['total_input_tokens']); ``` ## Conversations A `Conversation` keeps a message history between requests: ```php use Taphra\Ai\AI; $chat = AI::conversation('support-42', 'cache'); // backends: session (the default), cache, memory $chat->addSystemMessage('You are the support assistant of an online shop.'); $chat->addUserMessage('Where is my order?'); $reply = AI::complete($chat->getMessages()); $chat->addAssistantMessage($reply['content']); echo $chat->count(), " messages, about ", $chat->estimatedTokens(), " tokens\n"; ``` | Backend | Where the history lives | |---|---| | `session` | The user's session (started on first use); the default of `AI::conversation()` | | `cache` | The app cache (see [cache](cache.md)), for one hour | | `memory` | The current request only | When a new user message would take the history past its token budget (100000 estimated tokens, about four characters each; set another as the third argument of `new Conversation($key, $backend, $maxTokens)`), the oldest messages are dropped. The system message is kept. `addImageMessage($text, $images)` adds a user message with image URLs or base64 images, and `clear()` empties the history. Register another store with `Conversation::registerBackend('name', fn() => new MyStore())`, where `MyStore` implements `ConversationStoreInterface` (`get()` and `put()`). The key names the history: build it from something the user cannot choose freely, such as their user id or session id, so one user cannot read another's conversation. ## Prompt templates A prompt template is a file in `app/Prompts/` that returns a `Prompt` subclass. `php taphra make:prompt summarise` writes a stub with a `{topic}` placeholder to replace. ```php ```php use Taphra\Ai\Prompt; $messages = Prompt::load('summarise') ->with(['style' => 'three-bullet', 'text' => 'Taphra 1.0 ships today.']) ->toMessages(); echo $messages[0]['content'], "\n"; // You write three-bullet summaries for busy readers. ``` `{name}` placeholders are replaced with the values you pass, as they are; a placeholder without a value stays in the text. `render()` returns the user prompt alone. Values from users go into the prompt unchanged, so the model sees anything they wrote, instructions included. ## Embeddings `embed()` returns a vector for a string, or a list of vectors for a list of strings: ```php use Taphra\Ai\AI; $vector = AI::provider('openai')->embed('A small, explicit PHP framework.'); echo count($vector), " dimensions\n"; ``` OpenAI uses `text-embedding-3-small` unless you pass `['model' => ...]`. Ollama calls `/api/embeddings` once per string with the configured model. Anthropic has no embeddings API: `embed()` on the Anthropic provider calls Voyage AI (`voyage-3` by default) with `voyage_api_key` or the `VOYAGE_API_KEY` environment variable. ## Fallback and caching `AI::fallback()` tries providers in order. An `AiException` (an HTTP error, a timeout, an invalid answer) moves on to the next provider; any other exception is thrown at once. ```php use Taphra\Ai\AI; $reply = AI::fallback('anthropic', 'openai') ->complete([['role' => 'user', 'content' => 'Summarise HTTP 529 in five words.']]); echo $reply['content'], "\n"; // answered by openai: the first provider was overloaded ``` `stream()` falls back too, but only before the first chunk: once text has reached the caller, an error is thrown rather than starting again with another provider. `AI::withCache()` keeps `complete()` answers in the app cache, keyed on the messages, the options and the provider name: ```php use Taphra\Ai\AI; $cached = AI::withCache('anthropic', 600); // TTL in seconds; 0 keeps answers until the cache is cleared $question = [['role' => 'user', 'content' => 'Which HTTP status means Too Many Requests?']]; $first = $cached->complete($question); // calls the API $second = $cached->complete($question); // served from the cache echo $second['content'], "\n"; ``` `stream()` and `embed()` are not cached, errors are not cached, and a cache failure sends the call to the provider. The key does not include an output schema or a tool list set on the provider, so use the cache for plain completions. ## Errors | Exception | Thrown when | |---|---| | `AiException` | Base class: an HTTP error answer (with the provider's message), a connection error or timeout, an invalid response, an error event in a stream, an unknown provider name | | `AiRateLimitException` | HTTP 429 after every retry (`rate_limiting.retry_attempts`) | | `AiStructuredOutputException` | A structured answer was declined, cut off, not JSON, or did not match the schema | | `AiMaxIterationsException` | An agent run reached its iteration limit | All are in `Taphra\Ai`. A rate-limited `complete()` is retried with exponential backoff; streamed requests are not retried. ## Logging With `logging.enabled` on (the default), each request adds one line to `app/tmp/Log/ai.log`: the time, the provider, the URL, the model, and the token usage, or the error when the request failed. Prompts and answers often hold personal data, so they are written only when you turn on `logging.payloads` (with the `logging.redact_fields` keys replaced): ```yaml # app/Config/ai.yml logging: enabled: true # false writes nothing payloads: true # add each request and answer (off by default) ``` ## Testing Providers send their requests through an HTTP transport. `FakeTransport` (`Taphra\Ai\Http`) replays queued responses instead of calling the network and records every request, so a test can check both the answer and the exact body that was sent. `AiConfig::snapshot()` and `AiConfig::restore()` swap the configuration for the test and put it back afterwards; `AI::reset()` drops the provider instances built from the old one: ```php use Taphra\Ai\AI; use Taphra\Ai\AiConfig; use Taphra\Ai\Http\FakeTransport; $fake = (new FakeTransport())->queueJson([ 'content' => [['type' => 'text', 'text' => 'Bonjour']], 'stop_reason' => 'end_turn', 'usage' => ['input_tokens' => 9, 'output_tokens' => 2], ]); $saved = AiConfig::snapshot(); AiConfig::restore(['config' => [ 'default_provider' => 'anthropic', 'providers' => ['anthropic' => ['api_key' => 'test', 'transport' => $fake]], ], 'resolver' => null]); AI::reset(); $reply = AI::complete([['role' => 'user', 'content' => 'Say hello in French.']]); $sent = $fake->lastRequest()->json(); echo $reply['content'], ' / ', $sent['messages'][0]['content'], "\n"; // Bonjour / Say hello in French. AiConfig::restore($saved); AI::reset(); ``` `queueStream([...chunks])` replays a streamed response chunk by chunk, `queueJson($body, 429)` an error status, and `queueConnectionError()` a failed connection. `requests()` lists every request sent and `pending()` counts the responses not used yet. In an app, a provider can also take any `HttpTransport` as `'transport' => $transport` in its config, or through `$provider->withTransport($transport)`, for example to add a proxy or record traffic. --- Source: https://taphra.dev/docs/mcp/ # MCP server The Model Context Protocol (MCP) lets an AI client such as a desktop app, an IDE or an agent call into your application. Taphra serves methods of your controllers as MCP tools, resources and prompts: over stdio with `php taphra mcp:serve` for clients that start a local process, and over Streamable HTTP for remote clients. The server is part of the bundled `taphra/ai` package (`Taphra\Ai\Mcp`); [its README](../packages/ai/README.md#mcp-server) covers using it without the framework. ## Contents - [What the server implements](#what-the-server-implements) - [Declaring tools, resources and prompts](#declaring-tools-resources-and-prompts) - [Return values and errors](#return-values-and-errors) - [CRUD tools from a DataStore](#crud-tools-from-a-datastore) - [Serving over stdio](#serving-over-stdio) - [Serving over HTTP](#serving-over-http) - [Testing MCP code](#testing-mcp-code) ## What the server implements | Area | Supported | |---|---| | Protocol revisions | 2025-11-25, 2025-06-18, 2025-03-26 and 2024-11-05, negotiated in `initialize`. A client asking for another revision gets 2025-11-25. | | Methods | `initialize`, `ping`, `tools/list`, `tools/call`, `resources/list`, `resources/templates/list` (always empty), `resources/read`, `prompts/list`, `prompts/get` | | Lists | Cursor pagination, 100 items per page by default | | 2025-06-18 and later | Tool and resource `title`, tool `outputSchema`, `structuredContent` in tool results | | Transports | stdio (newline-delimited JSON-RPC) and Streamable HTTP (JSON responses) | The server answers requests; it never sends requests or notifications of its own. Sampling, elicitation, resource subscriptions, list-changed notifications and server-initiated SSE streams are not implemented. The stateless 2026-07-28 revision is not implemented either: its `server/discover` probe gets a "method not found" error, so clients that speak both revisions fall back to `initialize`. ## Declaring tools, resources and prompts A capability is a public method with one of three attributes: `#[McpTool]`, `#[McpResource]` or `#[McpPrompt]` (namespace `Taphra\Ai\Mcp`). Start with the generator: ```bash php taphra make:mcp Order ``` It writes `app/Controllers/OrderMcpController.class.php` with a placeholder tool, resource and prompt, and, the first time, the base class `app/Controllers/AppMcpController.class.php`: ```php ```php 1, 'customer' => 'Ada', 'total' => 42.5, 'status' => 'paid'], ['id' => 2, 'customer' => 'Linus', 'total' => 18.0, 'status' => 'open'], ]; #[McpTool( name: 'find_order', description: 'Find one order by id.', inputSchema: [ 'type' => 'object', 'properties' => ['id' => ['type' => 'integer', 'description' => 'Order id']], 'required' => ['id'], ], annotations: ['readOnlyHint' => true], )] public function findOrder(array $params): array { $id = (int) ($params['id'] ?? 0); foreach (self::ORDERS as $order) { if ($order['id'] === $id) { return $order; } } throw new McpToolException("No order with id $id"); // this message reaches the client } #[McpResource(uri: 'orders://open', name: 'Open orders', description: 'Orders not paid yet', mimeType: 'application/json')] public function openOrders(array $params): array { return array_values(array_filter(self::ORDERS, fn(array $o) => $o['status'] === 'open')); } #[McpPrompt( name: 'summarise_order', description: 'Ask for a summary of one order', arguments: [['name' => 'id', 'description' => 'Order id', 'required' => true]], )] public function summariseOrder(array $params): string { return 'Summarise order #' . (int) $params['id'] . ' for the support team.'; } } ``` Every method receives one array: the tool's `arguments`, the prompt's `arguments`, or `['uri' => ...]` for a resource. The attribute parameters: | Attribute | Parameters | |---|---| | `McpTool` | `name`, `description`, `inputSchema` (JSON Schema, default an empty object), `title`, `outputSchema`, `annotations` (hints such as `readOnlyHint` or `destructiveHint`) | | `McpResource` | `uri`, `name`, `description`, `mimeType`, `title` | | `McpPrompt` | `name`, `description`, `arguments` (a list of `['name' => ..., 'description' => ..., 'required' => bool]`), `title` | Things to know: - The server does not check tool arguments against `inputSchema`; the schema tells the model what to send. Check and cast arguments in the method, as `findOrder()` does with `(int)`. Required prompt arguments are checked: a missing one is an "invalid params" error. - When you set `outputSchema`, the method must return an associative array that matches it. The server does not check it. - Methods with an MCP attribute are never URL actions: a request to `/orderMcp/findOrder` gets a 404. They are reached through the MCP server only. - Tool and prompt names, and resource URIs, must be unique. When two methods use the same one, the first discovered wins and `php taphra mcp:serve --list` lists the duplicate it skipped. ## Return values and errors | A tool returns | The client gets | |---|---| | a string | one text content block | | an associative array or an object | the JSON as a text block, and the same data as `structuredContent` (revision 2025-06-18 and later) | | a list, a number or a boolean | the JSON as a text block | | `null` | an empty result | | `['content' => [...], 'isError' => bool, 'structuredContent' => [...]]` | that result as it is | Collections and other objects are converted first: `JsonSerializable`, then `toArray()`, then iteration. A `DataStoreCollection` from `find()` can be returned as it is. An exception thrown by a tool becomes a tool result with `isError: true`, so the model can read the problem and try again. Only a `Taphra\Ai\Mcp\McpToolException` (or an `McpError`) sends its message to the client: throw one for messages such as "title is required". Any other exception is logged on the server with PHP's `error_log()` (stderr under `mcp:serve`) and the client gets a generic message, so database errors, paths and other internals stay on the server. Pass an `error_logger` callable in the server options to log elsewhere. A resource returns a string (sent as text with the resource's `mimeType`), an array (sent as JSON, `application/json` unless you set another type), or `['contents' => [['text' => ...], ['blob' => base64, 'mimeType' => ...]]]`. A prompt returns a string (one user message), a list of messages, or `['description' => ..., 'messages' => [['role' => 'user' | 'assistant', 'content' => ...]]]`. Protocol errors are JSON-RPC errors: | Code | When | |---|---| | -32700 | The message is not valid JSON | | -32600 | Not a valid JSON-RPC request | | -32601 | Unknown method | | -32602 | Unknown tool or prompt, a missing required prompt argument, malformed `arguments`, an invalid cursor | | -32002 | Unknown resource URI (the URI is in `error.data`) | | -32603 | A resource or prompt method threw: the message of an `McpToolException`, otherwise a generic message (the exception is logged) | ## CRUD tools from a DataStore `--from-datastore` reads a DataStore class (no database connection needed) and writes typed tools for it: ```bash php taphra make:mcp Post --from-datastore=PostDataStore ``` ``` Generated tools: list_posts, get_post, create_post, update_post, delete_post Generated resource: posts://list ``` The input schemas come from the DataStore's `$casts`, `$fillable` and a declared `$dataDefinition`; `created_at`, `updated_at` and `deleted_at` are left out of create and update. The generated methods call `find()`, `read()`, `save()` and `delete()`, so the DataStore's mass-assignment rules apply: `create_post` and `update_post` can only set `$fillable` columns. `list_posts` caps `limit` at 100, and `delete_post` carries the `destructiveHint` annotation. Every connected client can call every tool you serve. Delete the generated methods a client should not have, such as `delete_post`, before you connect one. ## Serving over stdio Check what will be served: ```bash php taphra mcp:serve --list ``` ``` MCP controllers directory: /var/www/my-app/app/Controllers Tools: 1 find_order Resources: 1 Open orders orders://open Prompts: 1 summarise_order ``` `php taphra mcp:serve` then reads JSON-RPC messages from stdin and writes one JSON line per response to stdout, until stdin closes. It serves every class under `app/Controllers` (subfolders included, `.php` or `.class.php`, namespaced or not) that has MCP methods, and every concrete `McpController` subclass. Only MCP messages go to stdout: anything a method prints, PHP warnings and uncaught errors go to stderr. The server name in `initialize` is `app_name` from `app/Config/app.yml`, unless an `McpController` subclass sets other options with `mcpServerOptions()` (see [Serving over HTTP](#serving-over-http)): `mcp:serve` uses them too, so both transports describe the server the same way. A session from a client, one message per line (responses shortened): ``` > {"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-11-25","capabilities":{},"clientInfo":{"name":"probe","version":"1"}}} < {"jsonrpc":"2.0","id":1,"result":{"protocolVersion":"2025-11-25","capabilities":{"tools":{"listChanged":false},"resources":{"subscribe":false,"listChanged":false},"prompts":{"listChanged":false}},"serverInfo":{"name":"my-app","version":"1.1.0"}}} > {"jsonrpc":"2.0","method":"notifications/initialized"} > {"jsonrpc":"2.0","id":2,"method":"tools/list"} < {"jsonrpc":"2.0","id":2,"result":{"tools":[{"name":"find_order","description":"Find one order by id.","inputSchema":{"type":"object","properties":{"id":{"type":"integer","description":"Order id"}},"required":["id"]},"annotations":{"readOnlyHint":true}}]}} > {"jsonrpc":"2.0","id":3,"method":"tools/call","params":{"name":"find_order","arguments":{"id":1}}} < {"jsonrpc":"2.0","id":3,"result":{"content":[{"type":"text","text":"{\"id\":1,\"customer\":\"Ada\",\"total\":42.5,\"status\":\"paid\"}"}],"isError":false,"structuredContent":{"id":1,"customer":"Ada","total":42.5,"status":"paid"}}} > {"jsonrpc":"2.0","id":4,"method":"tools/call","params":{"name":"find_order","arguments":{"id":9}}} < {"jsonrpc":"2.0","id":4,"result":{"content":[{"type":"text","text":"No order with id 9"}],"isError":true}} ``` The command boots the app like any other CLI command. With no `APP_ENV` set, that is production mode, with the production sections of your config files. stdio has no authentication: whoever can start the process can already read your files. ### Desktop clients Most desktop MCP clients take a JSON configuration with an `mcpServers` section. Add the server there, with the absolute path to your project's `taphra` script. The command works from any working directory. ```json { "mcpServers": { "my-app": { "command": "php", "args": ["/absolute/path/to/my-app/taphra", "mcp:serve"], "env": { "APP_ENV": "dev" } } } } ``` Leave out `env` to serve with the production configuration. Other clients that start a local process take the same command and arguments. ## Serving over HTTP An HTTP endpoint is a controller action: `McpController::handle()`. Route `POST`, `GET` and `DELETE` on one path to it. Method sections are top-level keys of `routes.yml` (see [routing](routing.md)): ```yaml # app/Config/routes.yml POST: /mcp: orderMcp/handle GET: /mcp: orderMcp/handle DELETE: /mcp: orderMcp/handle ``` Several MCP controllers can share one endpoint: in the constructor of the routed one, call `$this->discovery->discover(new OtherMcpController())`. ### Authentication The endpoint refuses every request with 401 until you choose how clients authenticate. Either set a shared token of at least 32 bytes, which clients send as `Authorization: Bearer ` and which is compared in constant time (a shorter token refuses every request, and the error log says why; the `mcp-server` template writes one to `.env` at `composer create-project`): ```bash export TAPHRA_MCP_TOKEN="$(php -r 'echo bin2hex(random_bytes(32));')" ``` or put it in `app/Config/ai.yml` as `mcp.token` (use a `${VARIABLE}` placeholder, not the token itself). Or override `authorizeMcp()` with your own check, for example against API keys stored in a table: ```php // app/Controllers/OrderMcpController.class.php protected function authorizeMcp(array $headers): bool { $key = $headers['x-api-key'] ?? ''; // header names are lower case return $key !== '' && ApiKeyDataStore::firstWhere(['key_hash' => hash('sha256', $key)]) !== null; } ``` MCP controllers extend `RestController`, not your `AppController`, so the skeleton's CSRF check does not apply to them; the token or your `authorizeMcp()` does that job. ### What the transport checks | Request | Answer | |---|---| | Not authorised | 401 with `WWW-Authenticate: Bearer` | | An `Origin` header that is not a loopback origin (`localhost`, `127.0.0.1`, `[::1]`) or listed in `mcp.allowed_origins` | 403. This protects a server on your machine from web pages (DNS rebinding). Requests without `Origin`, such as most non-browser clients, pass. | | POST whose `Content-Type` is not the media type `application/json` (parameters such as `charset` are fine), or has none | 415 | | POST with an `Accept` header that does not allow `application/json` | 406 | | POST `initialize` | 200, the result, and an `Mcp-Session-Id` header; 503 with `Retry-After` when 1000 sessions are already open | | Any other POST without `Mcp-Session-Id` | 400 | | An unknown or ended session | 404 | | An `MCP-Protocol-Version` header that differs from the negotiated revision | 400 | | A notification or a client response | 202, no body | | GET | 405: the server does not open server-to-client streams | | DELETE with `Mcp-Session-Id` | 204, the session ends | Responses are always `application/json`, never an SSE stream. Allow browser origins in `ai.yml`: ```yaml # app/Config/ai.yml mcp: token: "${TAPHRA_MCP_TOKEN}" allowed_origins: ["https://app.example.com"] ``` Sessions are JSON files in `app/tmp/mcp_sessions`, ended after an hour without a request; at most 1000 are open at a time. With several web servers behind a load balancer, override `mcpSessionStore()` to return a shared store (any `McpSessionStoreInterface`), or use sticky sessions. Override `mcpServerOptions()` to set the `name`, `version`, `title`, `instructions` or `page_size` the server reports; over HTTP the name defaults to "Taphra MCP Server". `php taphra mcp:serve` reports the same options (with several `McpController` subclasses, their options are merged in file order, a later file winning for the same key). ## Testing MCP code `McpServer` handles one JSON-RPC message in process, so a test can call a tool without a client or a transport. `McpDiscovery` collects the MCP methods of any object: ```php use App\Controllers\OrderMcpController; use Taphra\Ai\Mcp\McpDiscovery; use Taphra\Ai\Mcp\McpServer; $server = new McpServer((new McpDiscovery())->discover(new OrderMcpController())); $reply = $server->handleJson(json_encode([ 'jsonrpc' => '2.0', 'id' => 1, 'method' => 'tools/call', 'params' => ['name' => 'find_order', 'arguments' => ['id' => 2]], ])); $result = json_decode($reply, true)['result']; echo $result['structuredContent']['customer']; // Linus ``` `McpHttpTransport` takes the method, the headers and the body and returns an `McpHttpResponse` (`status`, `headers`, `body`), so the HTTP rules can be tested the same way. `McpMemorySessionStore` keeps sessions in memory: ```php use App\Controllers\OrderMcpController; use Taphra\Ai\Mcp\McpDiscovery; use Taphra\Ai\Mcp\McpHttpTransport; use Taphra\Ai\Mcp\McpMemorySessionStore; $discovery = (new McpDiscovery())->discover(new OrderMcpController()); $json = ['Content-Type' => 'application/json']; $init = json_encode(['jsonrpc' => '2.0', 'id' => 1, 'method' => 'initialize', 'params' => ['protocolVersion' => '2025-11-25']]); // No authorize callback: every request is refused. $closed = new McpHttpTransport($discovery, new McpMemorySessionStore()); echo $closed->handle('POST', $json, $init)->status, "\n"; // 401 $http = new McpHttpTransport($discovery, new McpMemorySessionStore(), [ 'authorize' => fn(array $headers): bool => McpHttpTransport::bearerTokenMatches($headers, 'test-token'), ]); $auth = $json + ['Authorization' => 'Bearer test-token']; $started = $http->handle('POST', $auth, $init); $session = $started->header('Mcp-Session-Id'); $call = $http->handle('POST', $auth + ['Mcp-Session-Id' => $session], json_encode([ 'jsonrpc' => '2.0', 'id' => 2, 'method' => 'tools/call', 'params' => ['name' => 'find_order', 'arguments' => ['id' => 1]], ])); echo $call->status, ' ', json_decode($call->body, true)['result']['structuredContent']['status'], "\n"; // 200 paid ``` To test the whole endpoint with routing and your `authorizeMcp()`, send requests through the app with `HttpTestCase` (see [testing](testing.md)). On that entry `McpController` reads the headers and the body of the request the test sends. This test uses the `/mcp` routes above and a token set for the test: ```php 'Bearer ' . self::TOKEN]; $this->postJson('/mcp', ['jsonrpc' => '2.0', 'id' => 1, 'method' => 'tools/list']) ->assertUnauthorized(); $started = $this->postJson('/mcp', [ 'jsonrpc' => '2.0', 'id' => 1, 'method' => 'initialize', 'params' => ['protocolVersion' => '2025-11-25'], ], $auth)->assertOk(); $session = $auth + ['Mcp-Session-Id' => $started->getHeader('Mcp-Session-Id')]; $this->postJson('/mcp', [ 'jsonrpc' => '2.0', 'id' => 2, 'method' => 'tools/call', 'params' => ['name' => 'find_order', 'arguments' => ['id' => 2]], ], $session) ->assertOk() ->assertJsonPath('result.structuredContent.customer', 'Linus'); $this->delete('/mcp', [], $session)->assertStatus(204); } } ``` Sessions are files in `app/tmp/mcp_sessions` here too; to keep them in memory during tests, override `mcpSessionStore()` in a test subclass of the controller. --- Source: https://taphra.dev/docs/ai-builder/ # AI builder `php taphra ai:build` turns a description in plain English into files in your app: it plans them, then writes them with your approval. Every file change (including the files a `make:*` generator creates), and every command that is not on a short allow-list, is shown to you first and applied only when you say yes. Every session keeps a receipt, so `php taphra ai:rollback` can undo it. `php taphra ai:fix` does the same for one error. The AI builder is a preview feature: it works, and its behaviour may still change in minor releases. It runs code that a language model wrote, on your machine. Read what it proposes before you approve it, and use version control. ## Contents - [Commands](#commands) - [Approving changes](#approving-changes) - [How a build runs](#how-a-build-runs) - [Receipts and rollback](#receipts-and-rollback) - [What the tools may touch](#what-the-tools-may-touch) - [Configuration](#configuration) - [Known limitations](#known-limitations) - [Example session](#example-session) ## Commands ### `ai:build`: build or extend an app ```bash php taphra ai:build php taphra ai:build "a blog with posts, tags, and comments" ``` | Option | Description | |---|---| | `-p`, `--provider=NAME` | Provider from `app/Config/ai.yml` to use (`anthropic`, `openai`, `ollama`) | | `-m`, `--model=NAME` | Model for every call of this session | | `--port=PORT` | Port of the test URL shown at the end (default 8080) | | `--dontaskforpermissions` | Apply every file change without asking, and run Taphra commands and plain file tools (`ls`, `cat`, `cp`, `mv`, `rm`, ...) without asking, including commands that run the code just written. Any other program is refused. It prints a warning at the start and before each command. Blocked commands stay blocked. Use it only in a throwaway copy of a project. | | `--continue` | Resume the most recent session instead of starting a new one | Slash commands at the "What would you like to add?" prompt: | Command | Effect | |---|---| | `/rollback` | Undo everything this session changed | | `/receipt` | Show what this session has changed so far | | `/exit` | End the session | ### `ai:fix`: diagnose and fix an error ```bash php taphra ai:fix php taphra ai:fix "Undefined variable \$post in PostController.class.php on line 42" php taphra ai:fix "$(tail -n 40 app/tmp/Log/app.log)" --provider=openai ``` Without an argument, `ai:fix` asks you to paste the error. It reads the files named in the error for context and proposes the smallest change that fixes it. Each change is shown and applied only when you approve it. Changed PHP files are checked with `php -l`, and one more correction pass runs if syntax errors remain. Fixes are recorded in a receipt too, so `php taphra ai:rollback` undoes them. It takes `--provider`, `--model` and `--dontaskforpermissions` like `ai:build`. Pass the error as an argument, as above, rather than piping it in. Input on a pipe is read only with `-n` (`--no-interaction`), and with `-n` every change is refused, so you get the diagnosis and the proposed patch without any file being written (see [Approving changes](#approving-changes) for the commands that still run). ### `ai:rollback`: undo a session ```bash php taphra ai:rollback # undo the most recent session php taphra ai:rollback 20261129143200 # undo a session by its receipt ID php taphra ai:rollback --list # list the saved receipts and their status php taphra ai:rollback --yes # skip the confirmation question php taphra ai:rollback --force # also undo files you edited after the session ``` ## Approving changes Before each file change the builder prints what it is about to do and asks: ``` Confirm: Create app/Controllers/PostController.class.php (6 lines, 110 bytes) + add a page that lists posts by tag ``` When the current history has used more than 80,000 tokens, it is replaced by a summary of what was built and counting starts again, so work can go on. ### Project context Before every model call, the builder reads the project and adds its current state to the system prompt: | Context | Source | |---|---| | Next migration ID | `app/Migrations/migration_*.php` (sequential or timestamp IDs) | | Tables already created | `CREATE TABLE` statements and `SchemaBuilder::create()` calls in migrations | | App namespace | The `namespace` of the app's controllers (or the `app/` entry in composer.json's PSR-4 map). Namespaced apps get namespaced examples with `use` lines and PSR-4 file names; apps with global classes get the classmap conventions | | Base classes | `AppController`, `AppDataStore` and the other `App*` base classes the project ships | | Existing DataStores | `app/DataStores/*.php` and `*.class.php`, with the table name from `$objectName` | | Existing controllers | `app/Controllers/*.php` and `*.class.php`, base classes left out | | Current routes | `app/Config/routes.yml` | | Database driver | `app/Config/databases.yml` or `app/Config/app.yml` | | Installed packages | `composer.json` (`taphra/*` and relevant third-party packages) | ## Receipts and rollback Every session that changes something writes a receipt to `app/tmp/ai_builds/{id}.json`. It is saved before the first change and again after every change, so a build that fails or is interrupted half way can still be undone; a failed build prints the receipt ID to use. Each path is recorded once, with its state before the session first touched it: - **Created files** did not exist before; rollback deletes them. - **Overwritten files** existed and were replaced; the original content is kept and restored. - **Patched files** existed and were changed with search and replace; the original content is kept and restored. - **Migrations run** during the session are rolled back with `php taphra migration down {last ID before the session}`. Files created by commands (for example `make:controller`) are recorded as created files too. Rollback is careful: - A file you edited after the session is left as it is and listed, unless you pass `--force`. - Every path in the receipt is checked again before anything is touched, and only files under `app/` inside the project are restored or deleted. - A receipt that was fully rolled back is marked so, and is not offered again. ## What the tools may touch | Tool | What it does | Limits | |---|---|---| | `create_file` | Write a new file or replace one | Asks first. Only under `app/`, never in `app/tmp/ai_builds/` | | `update_file` | Patch an existing file with search and replace | Asks first. Only under `app/` | | `read_file` | Read a project file | Inside the project; `.env` files and `.git/` cannot be read | | `list_files` | List a directory | Inside the project; skips `.git/`, `vendor/`, `node_modules/` and `.env` files; links are listed, not followed | | `run_command` | Run one command | See below | What `read_file` returns is sent to the AI provider. Keep secrets in environment variables, not in files under `app/Config/`. Paths from the model must be relative to the project root. Absolute paths, `~`, stream wrappers such as `phar://`, NUL bytes, `..` segments that climb above the project, `:` in a segment and Windows short names (a `~` followed by a digit, as in `GIT~1`) are rejected. Symbolic links are followed one component at a time, and a link that leads outside the project (or nowhere) is rejected. Missing directories are created only after the whole path has been checked. ### Commands `run_command` never uses a shell. The command string is split into arguments (single quotes, double quotes and backslash escapes work as usual), and shell syntax is refused: pipes, redirections, `;`, `&&`, `$VAR`, `$(...)`, backticks, wildcards and line breaks. Each command runs with a timeout of 120 seconds. Taphra commands may be written with or without the `php taphra` prefix. They run through the project's own CLI script with the PHP binary that runs the builder. Other programs run with the project root as their working directory. | Category | Commands | Behaviour | |---|---|---| | **Allow-list** | `migrate` and `migrate --dry-run`; `migration status`; `route:list`; `list`; `help`; `ls` inside the project; `php -l` on a project file | Runs without asking, until the builder has written a file in the session (see below) | | **Generators** | `make:*` generators (`make:controller`, `make:model`, `make:datastore`, `make:migration`, `make:crud`, `make:mcp`, `make:tool` and the others) | Create files, so they ask as a file change and run only if you approve. Those that write under `app/`, with plain names and options, need no other approval; any other arguments or generator ask as a command too. With `-n` they never run; with `--dontaskforpermissions` they run without asking | | **Ask** | Everything else that is not blocked, for example `composer show`, `tinker`, `rm`, `cp` | Shows the exact command and runs it only if you approve. With `--dontaskforpermissions`, only Taphra commands and plain file tools run; any other program is refused | | **Blocked** | Shells and wrappers that run another program (`sh`, `bash`, `env`, `xargs`, `nohup`, `timeout`, `flock`, `tmux`, `screen`, `setarch`, ...); Windows scripts and shells (`.bat`, `.cmd`, `.ps1`, `cmd.exe`, `powershell.exe`; `.exe` names are matched like the plain names); interpreters and tools that run code they are given (`php` with a script or `-r`, `awk`, `sed`, `perl`, `python`, `node`, `jq`, ...); `composer` except read-only commands such as `show` and `validate`; build tools and package managers (`make`, `npm`, `pip`, ...); database shells (`sqlite3`, `mysql`, `psql`); archive tools (`tar`, `unzip`, `zip`, ...); network tools (`curl`, `wget`, `ssh`, `nc`, ...); privilege tools (`sudo`, `su`, ...); `chmod`, `docker` and similar system tools; `find` with `-exec`, `-ok` or `-delete`; `git` (repository config, hooks and aliases can run commands, so the builder never runs it; run git yourself); interpreters such as `Rscript` and `erb`; programs inside `app/`; arguments that name files that may hold secrets (`.env`, `.git`, Windows short names); and any argument that points outside the project, including values glued to short options such as `-C..` | Never runs, in any mode | Once `create_file` or `update_file` has written a file in the session, every command asks first, including allow-listed ones: `migrate` loads the migrations that were written, and every Taphra command loads the app. This carries over to `ai:build --continue` when the earlier session wrote files. `--dontaskforpermissions` turns "Ask" into "runs with a warning". It never turns "Blocked" into anything else. ## Configuration The builder uses the providers in `app/Config/ai.yml` (see [AI](ai.md#configuration)). When the file is missing, the first `ai:build` or `ai:fix` run asks three questions (provider, API key, model) and writes it: ```yaml default_provider: anthropic providers: anthropic: api_key: "${ANTHROPIC_API_KEY}" model: claude-opus-4-6 max_tokens: 4096 ``` The key itself goes to `.env` when it is not already in the environment. Taphra does not read `.env` at runtime, so export the variable in your shell before the next session. Pass `--provider=NAME` to use another configured provider for one session, or `--model=NAME` for another model of the same provider. ## Known limitations - The conventions the builder gives the model are those of apps with global classes in `.class.php` files and no `namespace` line. Apps made from the 1.0 skeleton use the `App\` namespace (`App\Controllers\AppController`), so a generated controller or DataStore needs the matching `namespace` line and `composer dump-autoload` before it loads. Review generated classes for this before you approve them. - Migrations run during a session are found through the file state backend (`app/Migrations/migration_state.json`, the default). With `state.backend: database` in `migrations.yml`, rollback does not undo them; run `php taphra migrate:down` yourself. - The test URL at the end assumes `php taphra serve` on the port given with `--port`. ## Example session ``` Taphra AI Builder powered by anthropic Type your description, then press Enter. Slash commands: /rollback /receipt /exit What would you like to build? > a REST API for a task manager with projects and tasks Planning… A task manager REST API with CRUD for projects and tasks, plus status filtering. Files to create: app/Migrations/migration_20261129143200_CreateProjectsTable.php migration app/DataStores/ProjectDataStore.class.php datastore app/Controllers/ApiProjectsController.class.php controller Proceed with this plan? [Y/n] Building… Confirm: Create app/Migrations/migration_20261129143200_CreateProjectsTable.php (24 lines, 712 bytes) + ```yaml all: default: type: database connection: queue # a connection from databases.yml prod: default: type: redis host: 127.0.0.1 port: 6379 database: 0 # password: secret ``` | `type` | Backend | How a worker waits for jobs | Settings | |---|---|---|---| | `database` | a table `_queue_jobs_` in any SQL connection, created on first use | polls once a second | `connection`, `autoMigrate` (default `true`) | | `redis` | a Redis server, through Predis | `BRPOP`: wakes as soon as a job arrives | `host`, `port`, `database`, `password` | | `beanstalkd` | a beanstalkd server, through Pheanstalk | `reserve`: wakes as soon as a job arrives | `host`, `port`, `timeout` | The database driver needs nothing beyond a database, so it suits development and small apps. The connection it names is an entry of `app/Config/databases.yml`; for development a SQLite file is enough: ```yaml dev: queue: type: sqlite name: tmp/queue.sqlite # relative to the app folder host: "" port: "" user: "" password: "" ``` A queue holds several named channels (a beanstalkd "tube", a Redis list, a `queue` column value). Use them to separate kinds of work, such as `emails` and `reports`, and run a worker per channel. To add another backend, extend `Taphra\Queue\AbstractQueue`, name the class after the type (`type: sqs` loads `SqsQueue`) and put it in `app/Queue/` as `App\Queue\SqsQueue`. ## Writing a job A job is a class that implements `Taphra\Queue\JobInterface` and has a public static method for the worker to call. The method receives the job's parameters and returns `true` when the work is done. Returning `false` or throwing marks the attempt as failed. ```php ```php use App\Jobs\ExportReportJob; use Taphra\Queue\Queue; $jobId = Queue::connection('default')->push('reports', json_encode([ 'type' => 'job', 'name' => 'export_report', // shown in the worker's output 'class' => ExportReportJob::class, 'method' => 'handle', 'params' => ['2026-11'], // passed to handle() in order ])); ``` The parameters go through `json_encode()`, so pass ids and plain values, not objects: the job loads what it needs when it runs. Always pass the payload as a string; the drivers store a string. The same connection can read jobs directly, which is what a worker does: ```php use Taphra\Queue\Queue; $queue = Queue::connection('default'); $job = $queue->pull('reports', 0); // wait 0 seconds; null when the channel is empty $data = json_decode($job->getData(), true); $job->requeue(); // put it back, for the worker below ``` `pull()` reserves the job so no other worker takes it. After processing, call `done()` to remove it, `requeue()` to put it back, or `delete()` to mark it failed. ## Running a worker ```bash php taphra queue:work reports ``` The worker runs until it is stopped and prints a line per job, such as `[2026-11-30 09:15:02] Done: export_report`. | Option | Default | Meaning | |---|---|---| | `queue` (argument) | `queue.defaultQueue` from `app.yml`, else `default` | the channel to process | | `--connection` | `default` | the connection from `queue.yml` | | `--sleep` | `3` | seconds to wait for a job before checking again (the `BRPOP` timeout with Redis) | | `--tries` | `3` | attempts before a job is given up | | `--concurrency` | `1` | worker processes; more than one needs `ext-pcntl` | With `ext-pcntl` loaded, `SIGTERM` and `SIGINT` (Ctrl+C) let the current job finish before the worker exits. Without it the process stops at once, in the middle of a job if one is running. `php taphra queue:listen` is a development helper that restarts itself when a `.php` or `.yml` file in `app/` changes. It differs from `queue:work`: it reads the connection from the `queue:` key of `app.yml` (with a `type` and the driver's settings), not from `queue.yml`; it runs each job once, without retries; and after a change it starts the new listener in the background and exits, so its output no longer reaches your terminal. Restarting `queue:work` by hand after a change is often simpler. ## Retries and failed jobs When a job returns `false` or throws, the worker waits and puts it back: 1 second after the first attempt, then 2, 4 and so on, up to 60 seconds. The worker itself sleeps during that wait, so it processes no other job meanwhile. Attempts are counted inside the worker process, so a restarted worker starts counting again. After `--tries` attempts the job is given up: | Driver | A job that was given up | |---|---| | `database` | stays in `_queue_jobs_` with `status = 'failed'` | | `redis` | is removed | | `beanstalkd` | is buried, and stays in the tube until you delete or kick it | With the database driver, list failed jobs with SQL, for example `SELECT id, queue, payload FROM _queue_jobs_ WHERE status = 'failed'`. `php taphra queue:failed` does not list them yet: in 1.0 it only prints a reminder. ## Workers in production Run workers under a process manager (systemd, Supervisor, a container orchestrator) that starts them on boot and restarts them when they exit. A minimal systemd unit: ```ini # /etc/systemd/system/myapp-queue.service [Unit] Description=myapp queue worker After=network.target [Service] User=www-data WorkingDirectory=/var/www/myapp Environment=APP_ENV=prod ExecStart=/usr/bin/php taphra queue:work reports --tries=5 Restart=always [Install] WantedBy=multi-user.target ``` - A worker loads the code once, when it starts. Restart workers on every deploy (`systemctl restart myapp-queue`), or they keep running the old code. - Set `APP_ENV` for the worker as for the web server; an unset or unknown value means production. - Install `ext-pcntl` so a restart lets the current job finish. - A worker has no memory or job-count limit of its own. Long-running workers are restarted by the process manager; schedule a periodic restart if a job leaks memory. [deployment.md](deployment.md) covers the rest of a production setup. ## Limits in 1.0 - There is no delayed dispatch: a pushed job is available at once. For work that must happen later, use the [scheduler](scheduler.md). - A job that was running when its worker died is not retried automatically: with the database driver it stays `reserved`, with Redis it is gone. Beanstalkd releases it again after its time to run. --- Source: https://taphra.dev/docs/cache/ # Cache `Taphra\Cache\Cache` stores values between requests: results you compute, query results, and whole page output. It runs on files by default and on APCu, Memcache or Redis when you configure one. Entries expire after a time to live, or when an [event](events.md) they subscribed to is emitted. The last section covers locks, which keep two processes from running the same job at once. ## Contents - [Choosing a driver](#choosing-a-driver) - [Storing and reading values](#storing-and-reading-values) - [Caching function output](#caching-function-output) - [Caching query results](#caching-query-results) - [Invalidating with events](#invalidating-with-events) - [Caching page output](#caching-page-output) - [Clearing the cache](#clearing-the-cache) - [A PSR-16 cache for libraries](#a-psr-16-cache-for-libraries) - [Locks](#locks) ## Choosing a driver The driver is `caching.method` in `app/Config/app.yml`. The skeleton uses the file driver: ```yaml all: caching: method: file # file | apc | memcache | redis ``` | `method` | Stores entries in | Needs | |---|---|---| | `file` | `app/tmp/Filecache/`, one file per entry | a writable `app/tmp` | | `apc` | APCu shared memory of the PHP server | `ext-apcu` | | `memcache` | a Memcache server | `ext-memcache` and `caching.servers` | | `redis` | a Redis server, through Predis | `caching.servers` | A Redis cache for production: ```yaml prod: caching: method: redis servers: main: host: 127.0.0.1 port: 6379 database: 1 password: "" ``` `database` defaults to 0. The cache uses one Redis server: list one entry under `servers` (for several machines, the address of a Redis Cluster, Sentinel or proxy endpoint); a list of more than one is refused with an error, since spreading one cache over independent servers would miss and leave stale entries. The file and APCu drivers keep entries per machine. With several web servers behind a load balancer, use Redis or Memcache so that every server sees the same entries. When `apc` or `memcache` is configured and its extension is missing, `Cache::getInstance()` logs a warning and returns `null`. ## Storing and reading values `Cache::getInstance()` returns the shared cache. Times to live are in seconds; `0` means the entry does not expire. ```php use Taphra\Cache\Cache; $cache = Cache::getInstance(); $cache->write('banner.text', 'Free shipping this week', 600); echo $cache->read('banner.text'), "\n"; // Free shipping this week $cache->delete('banner.text'); var_dump($cache->read('banner.text')); // bool(false) ``` `read()` returns `false` for a missing or expired entry, so a stored `false` cannot be told apart from a miss. Store arrays or strings, or use `remember()`, which tracks hits itself: ```php use Taphra\Cache\Cache; $stats = Cache::getInstance()->remember('dashboard.stats', 300, function (): array { // Runs only when the entry is missing or expired. return ['orders' => 128, 'refunds' => 3]; }); ``` `remember()` takes seconds, a `DateInterval`, or `null` for no expiry. The file driver refuses `null` values (it throws `InvalidArgumentException`), so a `remember()` callback must not return `null`; return `false` or an empty array instead. Values are stored with `serialize()`: arrays, scalars, DataStore rows and collections, `DateTime` and `DateTimeImmutable` round-trip. Any other object comes back as `__PHP_Incomplete_Class`, because the cache reads values back with an allow list of classes, never with unrestricted `unserialize()`; store such data as arrays. Closures and open resources (database handles, file pointers) cannot be cached. ## Caching function output `getCachedFunctionOutput($callable, $params, $rules)` calls a function once, caches its return value, and serves later calls from the cache. The key is made from the callable and its arguments, so each argument list gets its own entry. A `CacheRules` object holds the time to live and the events that invalidate the entry. ```php use Taphra\Cache\Cache; use Taphra\Cache\CacheRules; final class Reports { public static int $runs = 0; public static function monthlyTotals(string $month): array { self::$runs++; return ['month' => $month, 'total' => 5400]; // an expensive query in a real app } } $rules = new CacheRules(['order.paid' => []], 3600); // [events => params], time to live $cache = Cache::getInstance(); $a = $cache->getCachedFunctionOutput([Reports::class, 'monthlyTotals'], ['2026-11'], $rules); $b = $cache->getCachedFunctionOutput([Reports::class, 'monthlyTotals'], ['2026-11'], $rules); // Reports::$runs === 1: the second call came from the cache ``` The callable must have a name: a function name, `[ClassName::class, 'method']` or `[$object, 'method']` (keyed by the object's class). A closure is refused, because the key is built by serialising the callable. Passing `null` as the rules calls the function without caching. ## Caching query results `find()` and `findCount()` on a DataStore take a `CacheRules` object as their last argument and cache the rows they read: ```php use Taphra\DatabaseConnection; use Taphra\SchemaBuilder; (new SchemaBuilder(DatabaseConnection::load('app_master')))->create('products', function ($t) { $t->id(); $t->string('name', 100); $t->integer('stock')->default(0); }); ``` ```php ```php use App\DataStores\ProductDataStore; use Taphra\Cache\CacheRules; $products = new ProductDataStore(); $products->save(['name' => 'Mug', 'stock' => 3]); $inStock = new CacheRules(['product.changed' => []], 600); $before = $products->findCount(['stock >' => 0], $inStock); // 1, now cached $products->save(['name' => 'Cap', 'stock' => 5]); $cached = $products->findCount(['stock >' => 0], $inStock); // still 1, from the cache // find($conditions, $count, $offset, $orderField, $order, $skipHooks, $cacheRules) $rows = $products->find(['stock >' => 0], 0, 0, 'name', 'ASC', false, $inStock); ``` The cache key is the query (table, conditions, order, limit) together with the DataStore class and the database it runs on (the connection name, driver, host, port and database or SQLite file, never the credentials): the same query on two databases, or through two DataStore classes, has two entries. Writes do not invalidate it: emit the event the rules name after a change (next section), or keep the time to live short. ## Invalidating with events The cache listens to every `Event::emit()`. Emitting an event deletes the entries whose `CacheRules` name that event with no parameters: ```php use App\DataStores\ProductDataStore; use Taphra\Cache\CacheRules; use Taphra\Event; Event::emit('product.changed'); $fresh = (new ProductDataStore())->findCount(['stock >' => 0], new CacheRules(['product.changed' => []], 600)); // 2: the entry was deleted, so the query ran again ``` An entry can also subscribe to an event with parameters, for example one product's page: `new CacheRules(['product.changed' => ['id' => 7]], 600)`. `Event::emit()` passes only the event name to the cache, so these entries are deleted by calling the cache directly with the same parameters: ```php use Taphra\Cache\Cache; Cache::getInstance()->triggerCacheEvent('product.changed', ['id' => 7]); // true when it deleted something ``` A good place for the `Event::emit()` call is the DataStore's `afterSave()` and `afterDelete()` hooks, so every write announces itself (see [events.md](events.md#events-and-datastores)). ## Caching page output `app/Config/cache.yml` caches the output of controller actions without changing the controllers. Each entry is `.` in lower case, with a time to live and the events that invalidate it: ```yaml all: catalog: index: ttl: 600 events: product.changed: ~ # ~ means no parameters ``` ```php toArray(), 'name'); return '
  • ' . implode('
  • ', array_map('e', $names)) . '
'; } } ``` The first request to `/catalog` runs the action and stores its output; later requests get the stored output until it expires or `product.changed` is emitted. Know what the key contains before you cache a page: - The key is the controller, the action, the route parameters, the whole query string, the host, the theme and the request headers `Accept`, `Accept-Language`, `HX-Request`, `HX-Target` and `X-Requested-With`. The session and the logged-in user are not part of it: every anonymous visitor gets the same output. Cache only pages that are the same for everyone. - Only anonymous GET requests use the cache: a request with a session cookie, a remember-me cookie or an `Authorization` header always runs the action, and a response that starts a session, sets a cookie or has a status other than 200 is not stored. - The entry holds the body, the status and the headers that say how to read it: `Content-Type`, `Content-Language`, `Content-Disposition`, `Content-Security-Policy` (and its report-only form), `X-Content-Type-Options`, `X-Frame-Options`, `Referrer-Policy`, `Permissions-Policy`, the `Cross-Origin-*-Policy` headers, `Vary`, `Link` and htmx's `HX-*` headers. A hit sends them again, so a cached JSON response stays `application/json`. Other headers (request ids, cookies) are not stored. ## Clearing the cache `Cache::getInstance()->clear()` deletes the app's entries: the files in `app/tmp/Filecache/` for the file driver, and the keys that carry the app's prefix for APCu and Redis. Memcache has no prefixes, so `clear()` flushes the whole Memcache server. From the command line: ```bash php taphra cache:clear ``` `cache:clear` also deletes the compiled configuration and translation caches in `app/tmp/config_cache/` and `app/tmp/lang_cache/`; they are rebuilt on the next request. An edited YAML file does not need it: the config caches follow the files' modification time and size (see [deployment.md](deployment.md)). ## A PSR-16 cache for libraries Every driver implements `Psr\SimpleCache\CacheInterface`. When a library asks for a PSR-16 cache, create a driver directly: ```php use Taphra\Cache\FileCacher; $psr16 = new FileCacher(); // the same app/tmp/Filecache/ folder $psr16->set('rates.eur', 1.08, 3600); $rate = $psr16->get('rates.eur'); // 1.08 $missing = $psr16->get('rates.gbp', 'n/a'); // 'n/a' ``` PSR-16 rules apply on this interface: keys may not contain `{}()/\@:`, and an invalid key throws `Taphra\Cache\InvalidCacheKeyException`. ## Locks `Taphra\Lock\Lock` makes sure only one process runs a piece of work at a time: a nightly import, a report, a scheduled task that may still be running when the next one starts. ```php use Taphra\Lock\Lock; if (Lock::getLock('nightly-import')) { try { echo "Importing\n"; // the exclusive work } finally { Lock::releaseLock('nightly-import'); } } else { echo "An import is already running\n"; } ``` `getLock()` does not wait: it returns `true` when it took the lock and `false` when another process holds it. Always release the lock in a `finally` block. A lock is also released when the process that holds it exits. Two drivers exist. Choose one with `lock.method` in `app.yml`, or per call with `Lock::getLock('name', LockType::File)` (`use Taphra\Lock\LockType`). | Driver | How it locks | Scope | |---|---|---| | `file` (default) | `flock()` on a file named after the lock in the system temporary directory | one machine | | `database` | a lock held on the connection you name: `GET_LOCK()` on MySQL and MariaDB, a session advisory lock on PostgreSQL, a row in a `_locks_` table on SQLite | every machine using that database | ```yaml all: lock: method: database config: app_master # a connection from databases.yml timeout: 5000 # milliseconds to wait for a held lock (default 0: do not wait) ttl: 3600 # SQLite only: seconds before a lock expires (default 3600) ``` On MySQL, MariaDB and PostgreSQL the lock is freed when the connection closes. On SQLite the row expires after `ttl` seconds, so a crashed holder does not block the name for ever: keep `ttl` longer than the work the lock protects. Other database types throw an exception. Lock names become file names for the file driver, so use letters, digits, dots and dashes. --- Source: https://taphra.dev/docs/events/ # Events `Taphra\Event` is an in-process event bus: one part of the app announces that something happened, other parts react to it. Listeners run synchronously, inside the same request, before `emit()` returns. For slow work (sending mail, calling an API), have the listener push a job to a [queue](queues.md). ## Listening and emitting Register a listener with `Event::on()` and announce the event with `Event::emit()`. Event names are free-form strings; a dotted `noun.verb` style (`order.paid`, `user.signed_up`) works well with wildcards. ```php use Taphra\Event; Event::on('order.paid', function (array $order): void { echo "Receipt for order {$order['id']}\n"; }); $order = ['id' => 42, 'total' => 1990]; $called = Event::emit('order.paid', [$order]); // prints "Receipt for order 42" // $called === 1: emit() returns the number of listeners it called ``` ### How the payload reaches the listener `emit(string $event, mixed $payload = null)` passes the payload in one of two ways: - a value that is not an array is the listener's only argument: `Event::emit('invoice.sent', $invoiceId)`; - an array is spread into positional arguments, and its keys are ignored. So an array you want to pass as one argument goes inside a list, as `[$order]` above. Spreading is useful for several values: ```php use Taphra\Event; Event::on('user.signed_up', function (string $email, string $source): void { echo "{$email} signed up from {$source}\n"; }); Event::emit('user.signed_up', ['ada@example.com', 'newsletter']); // prints "ada@example.com signed up from newsletter" ``` Emitting `['id' => 42, 'total' => 1990]` without the extra list would call the listener with `42` and `1990`. ## Wildcards and catch-all listeners A pattern that ends in `.*` matches every event name that starts with the part before the `*`: `refund.*` matches `refund.requested`, `refund.approved` and `refund.approved.partial`. Only this trailing form is supported. `Event::onAny()` registers a listener for every event. It receives the event name first and the payload as given, without spreading: ```php use Taphra\Event; $audit = []; Event::on('refund.*', function (array $refund) use (&$audit): void { $audit[] = "refund event for order #{$refund['order_id']}"; }); Event::onAny(function (string $event, mixed $payload) use (&$audit): void { $audit[] = "saw {$event}"; }); Event::emit('refund.requested', [['order_id' => 42]]); // $audit === ['refund event for order #42', 'saw refund.requested'] ``` ## Order, priorities and errors - Listeners registered with the same name or pattern run in the order they were registered. - Listeners are grouped by the name or pattern they were registered with; the groups run in the order each one got its first listener. If `order.*` got its first listener before `order.paid` did, the `order.*` listeners run first. - `onAny()` listeners run after all the others. - There are no priorities. When the order matters, register the listeners in that order, or have one listener call the next step itself. - An exception thrown by a listener leaves `emit()`: the remaining listeners do not run, and the caller sees the exception. ## Removing listeners `Event::off($event, $listener)` removes one listener; it compares by identity, so keep the closure in a variable. `Event::off($event)` removes every listener of that name or pattern. `Event::registered()` lists the names and patterns that have listeners. ```php use Taphra\Event; $notify = function (array $order): void { echo "notify\n"; }; Event::on('order.cancelled', $notify); Event::off('order.cancelled', $notify); $calledAfterOff = Event::emit('order.cancelled', [['id' => 42]]); // 0 ``` `Event::flush()` removes every listener, the `onAny()` ones included. It is meant for tests. It also removes the listener the cache registers on its first use (see [Events and the cache](#events-and-the-cache)), so event-driven cache invalidation stops for the rest of that process. ## Where to register listeners Register listeners once, when the app starts: in `app/bootstrap.php`, or in the `boot()` method of a service provider (see [container.md](container.md)). Do not register them inside a controller action. Under FrankenPHP worker mode one PHP process serves many requests: before each request the listener list goes back to what boot registered, so a listener added during a request lasts only for that request. ## Events and DataStores DataStores do not emit events by themselves. They have their own hooks (`beforeSave()`, `afterSave()`, `afterDelete()` and others) and observers, described in [datastores.md](datastores.md#hooks). To tell the rest of the app about a change, emit an event from a hook or an observer: ```php use Taphra\DatabaseConnection; use Taphra\SchemaBuilder; (new SchemaBuilder(DatabaseConnection::load('app_master')))->create('orders', function ($t) { $t->id(); $t->string('customer', 100); $t->integer('total'); }); ``` ```php ```php use App\DataStores\OrderDataStore; use Taphra\Event; Event::on('order.saved', function (array $order): void { echo "New order from {$order['customer']}\n"; }); (new OrderDataStore())->save(['customer' => 'Ada', 'total' => 1990]); // prints "New order from Ada" ``` ## Events and the cache Every `Event::emit()` also deletes the cache entries that subscribed to that event name, such as a cached query result or a cached page. [cache.md](cache.md#invalidating-with-events) shows how an entry subscribes. --- Source: https://taphra.dev/docs/scheduler/ # Scheduler The scheduler runs recurring tasks (a nightly cleanup, an hourly sync, a daily report) from one cron entry. You list the tasks in `app/Console/Kernel.php`; cron starts `php taphra schedule:run` every minute, and it runs the tasks that are due at that minute. ## Defining tasks `app/Console/Kernel.php` is a PHP file of `Schedule::` calls (or a `Kernel` class, below). A task is either a console command or a PHP callable, followed by a frequency: ```php daily()->at('03:30'); // A callable, run inside the schedule:run process. Schedule::call(function (): void { file_put_contents(APP_TMP_PATH . '/scheduler-heartbeat.txt', date('c')); })->everyMinute(); // Any cron expression: minute 15 of every sixth hour. Schedule::command('cache:clear')->cron('15 */6 * * *'); ``` The file may also declare a `Kernel` class and define the tasks in its `schedule()` method, which `schedule:run` and `schedule:list` call. The class lives in the app's namespace (`App\Console\Kernel`, or `APP_NAMESPACE\Console\Kernel` when the app sets another one; a global `Kernel` in an app whose `APP_NAMESPACE` is `''`). `schedule()` may be static or not, and when it takes a parameter it gets the `Taphra\Schedule` instance: ```php daily()->at('03:30'); } } ``` `schedule:list` and `schedule:run` both load the file, so both see the tasks. Command tasks can name your own console commands (see [cli.md](cli.md)) with their arguments, as in `Schedule::command('reports:send --period=week')`. ## Frequencies | Method | Cron expression | Runs | |---|---|---| | `everyMinute()` | `* * * * *` | every minute | | `everyFiveMinutes()` | `*/5 * * * *` | at minutes 0, 5, 10 ... | | `everyTenMinutes()` | `*/10 * * * *` | at minutes 0, 10, 20 ... | | `hourly()` | `0 * * * *` | at minute 0 of every hour | | `daily()` | `0 0 * * *` | at midnight | | `weekdays()` | `0 0 * * 1-5` | at midnight, Monday to Friday | | `weekends()` | `0 0 * * 6,0` | at midnight, Saturday and Sunday | | `weekly()` | `0 0 * * 0` | at midnight on Sunday | | `monthly()` | `0 0 1 * *` | at midnight on the first of the month | | `cron('m h dom mon dow')` | as given | as given | `at('HH:MM')` sets the hour and the minute of the expression, so it belongs after `daily()`, `weekdays()`, `weekends()`, `weekly()` and `monthly()`: `weekly()->at('07:05')` is `5 7 * * 0`. Call it after the frequency, since a frequency method replaces the whole expression. On `hourly()` it would also fix the hour and turn the task into a daily one. `cron()` takes a standard five-field expression (minute, hour, day of month, month, day of week) with lists, ranges and steps over `*` or a range: `*/15 * * * *`, `1-10/2 * * * *`, `5,10-20/5 * * * *`, `0 9 * * MON-FRI`. Steps count from the start of the range, as in cron (`*/2` in the day-of-month field is the 1st, 3rd, 5th and so on). When both day fields are restricted, a day matches if either one does. A malformed expression throws `InvalidArgumentException` when the task is defined. Times are read in PHP's default time zone (`date.timezone` in the CLI's `php.ini`), which may differ from the web server's. ## Running the scheduler Add one crontab entry on one server: ```bash * * * * * cd /var/www/myapp && APP_ENV=prod php taphra schedule:run >> /dev/null 2>&1 ``` Each run checks every task against the current minute and runs the due ones, one after another, then exits. It prints a line per task and a summary, or `No scheduled tasks were due.` `php taphra schedule:list` shows the tasks and their cron expressions: ```text +--------------------+--------------+----------------------+ | Command / Callback | Expression | Next Run | +--------------------+--------------+----------------------+ | cache:clear | 30 3 * * * | (cron: 30 3 * * *) | | [callable] | * * * * * | (cron: * * * * *) | | cache:clear | 15 */6 * * * | (cron: 15 */6 * * *) | +--------------------+--------------+----------------------+ ``` The "Next Run" column repeats the expression; it does not compute a date. In a test, or to run the due tasks from your own code, call the scheduler directly: ```php use Taphra\Schedule; $ran = Schedule::getInstance()->runDue(); // the number of tasks that ran ``` ## Testing your tasks `Schedule::command()` and `Schedule::call()` add to one schedule for the whole PHP process, and a test run is one process. `Schedule::reset()` forgets that schedule, so the next call starts an empty one. Call it in `setUp()` and `tearDown()`: each test then starts without the tasks of the tests before it and leaves none behind. ```php loadKernel(); // runs App\Console\Kernel::schedule() $this->assertSame( [['name' => 'cache:clear', 'expression' => '30 3 * * *', 'next' => '(cron: 30 3 * * *)']], $schedule->getTasks() ); } public function testACallbackTaskRuns(): void { $ran = false; Schedule::call(function () use (&$ran): void { $ran = true; })->everyMinute(); $this->assertSame(1, Schedule::getInstance()->runDue()); $this->assertTrue($ran); } } ``` The first test uses the `Kernel` class form of `app/Console/Kernel.php` above: after a reset, `loadKernel()` (which `runDue()` also calls) runs its `schedule()` again. A plain file of `Schedule::` calls is included once per process, so its tasks are not defined again after a reset; test such tasks by calling the code that defines them, as the second test does. A module that defines its tasks in a method of its own, `schedule(Schedule $schedule)`, is tested the same way: reset, call `schedule(Schedule::getInstance())`, then read `getTasks()`. ## Long tasks and overlapping runs The scheduler does not check whether the previous run of a task is still going. A task that can take longer than its interval should take a [lock](cache.md#locks), so that a second copy started by the next cron minute steps aside: ```php \App\Lib\FeedSync::run())->everyFiveMinutes(); ``` Tasks of one run also wait for each other, so a slow callable delays the tasks after it. Put long work in a console command (it runs in its own process) or push it to a [queue](queues.md) from a short task. A task that throws, or a command that exits with a non-zero code, is logged as an error with the category `Schedule`; the other due tasks still run, and `schedule:run` lists the failed tasks at the end and exits with 1. --- Source: https://taphra.dev/docs/email/ # Email `Taphra\Email` builds and sends messages through PHPMailer: SMTP, sendmail, qmail or PHP's `mail()`. Bodies are plain text or HTML with `{{ name }}` placeholders, or PHP templates from `app/Views/Emails/`. This page covers configuration, composing and sending, templates, attachments, sending from a queue worker, and seeing messages in development without sending them. ## Contents - [Configuration](#configuration) - [Composing and sending](#composing-and-sending) - [Placeholders](#placeholders) - [Templates](#templates) - [Attachments and headers](#attachments-and-headers) - [Sending in the background](#sending-in-the-background) - [Catching mail in development](#catching-mail-in-development) ## Configuration The transport is the `email` key of `app/Config/app.yml`. Without one, messages go through PHP's `mail()`, which needs a working local `sendmail`; most servers and containers have none. ```yaml prod: email: transport: smtp # smtp | sendmail | qmail | mail smtp: host: smtp.example.com port: 587 secure: tls # tls (STARTTLS) or ssl username: mailer@example.com ``` For `sendmail`, give the program's path as `sendmail: /usr/sbin/sendmail`. Every `new Email()` reads this configuration; `transport('smtp', [...])` overrides it for one message. In 1.0 an array passed to the constructor (`new Email([...])`) is not applied, and such a message falls back to PHP's `mail()`: use `new Email()` and `transport()` instead. Keep the SMTP password out of the YAML file. Read it from the server environment in `app/bootstrap.php`, which runs after the configuration is loaded. Replace the whole `app.email` array as shown: in 1.0, setting one nested key such as `app.email.smtp.password` makes later reads of `app.email` return only the keys set at run time, without the ones from `app.yml`. ```php // app/bootstrap.php use Taphra\Config; $email = Config::get('app.email'); if (is_array($email) && isset($email['smtp'])) { $email['smtp']['password'] = (string) getenv('SMTP_PASSWORD'); Config::set('app.email', $email); } ``` ## Composing and sending Every setter returns the message, so calls chain. `send()` returns `true`, or PHPMailer's error message as a string: ```php use Taphra\Email; $vars = ['name' => 'Ada & Charles', 'order' => ['id' => 1042]]; $result = (new Email()) ->to('ada@example.com', 'Ada Lovelace') ->from('shop@example.com', 'Example Shop') ->replyTo('support@example.com') ->subject('Your order has shipped') ->html('

Hello {{ name }},

Order {{ order.id }} is on its way.

', $vars) ->text("Hello {{ name }},\nOrder {{ order.id }} is on its way.", $vars) ->send(); if ($result !== true) { tphr_warning('Shipping email failed: ' . $result); } ``` - `to()`, `cc()`, `bcc()` and `replyTo()` take an address and an optional name; call them again to add more. `clearTo()`, `clearCc()`, `clearBcc()` and `clearReplyTo()` empty a list. - There is no default sender in the configuration: call `from()` on every message. - With both `html()` and `text()` the message has both parts. With `html()` alone, the plain-text part is made from the HTML. - `charSet()` (default `UTF-8`) and `encoding()` (default `8bit`) set the MIME options; `getMailer()` returns the PHPMailer instance for anything else. ## Placeholders Bodies set with `html()` and `text()` are content, never PHP: a ` ```php

Welcome,

Your account is ready. Sign in at .

``` The default layout for email templates is `app/Layouts/defaultemail.lyt.php`. The skeleton does not ship one, so create it before your first template email; the rendered template is in `$this->viewContent`: ```php viewContent ?>

Example Shop

``` ```php use Taphra\Email; $result = (new Email()) ->to('grace@example.com', 'Grace') ->from('shop@example.com', 'Example Shop') ->subject('Welcome to Example Shop') ->htmlTemplate('welcome', ['name' => 'Grace ', 'signInUrl' => 'https://example.com/login']) ->send(); ``` `htmlLayout('name')` picks another layout from `app/Layouts/`. Template and layout names are relative paths such as `welcome` or `orders/shipped`; anything else (`..`, an absolute path) throws `TaphraException`. Never build a template name from user input. With `htmlTemplate()` alone, the plain-text part is made from the rendered HTML. `textTemplate()` renders a separate text template, but in 1.0 its values are HTML-escaped too and it uses the same default layout as the HTML part, so a text template needs its own `textLayout()` and shows entities such as `&`. A template message cannot take a `text()` or `html()` body as well: setting one switches the message back to content bodies. ## Attachments and headers ```php use Taphra\Email; file_put_contents(APP_TMP_PATH . '/invoice-1042.csv', "item,amount\nMug,12.00\n"); $result = (new Email()) ->to('ada@example.com') ->from('billing@example.com', 'Example Shop') ->subject('Invoice 1042') ->text('Your invoice is attached.') ->attach(APP_TMP_PATH . '/invoice-1042.csv', 'invoice.csv') // path, name shown to the recipient ->header('X-Invoice-Id', '1042') ->send(); ``` `attach()` takes a path on the server; the file is read when the message is sent. `header()` adds a custom header. It refuses a header name with characters outside the RFC 7230 token set and a value containing a line break, so user input cannot inject extra headers. ## Sending in the background An SMTP round trip takes long enough that you rarely want it inside a request. Send from a [queue](queues.md) job: the request pushes the job, a worker sends the message, and a failed send is retried. ```php to($address, $name) ->from('shop@example.com', 'Example Shop') ->subject("Order {$orderId} has shipped") ->text("Hello {{ name }},\nOrder {{ id }} is on its way.", ['name' => $name, 'id' => $orderId]) ->send(); return $result === true; // false makes the worker retry the job } } ``` Push it from the request: ```php use App\Jobs\SendShippingEmail; use Taphra\Queue\Queue; Queue::connection('default')->push('emails', json_encode([ 'type' => 'job', 'name' => 'shipping_email', 'class' => SendShippingEmail::class, 'method' => 'handle', 'params' => ['ada@example.com', 'Ada', 1042], ])); ``` The worker (`php taphra queue:work emails`) calls `SendShippingEmail::handle('ada@example.com', 'Ada', 1042)`, as this does: ```php use App\Jobs\SendShippingEmail; $sent = SendShippingEmail::handle('ada@example.com', 'Ada', 1042); // true ``` `Email::queue()` does this for a whole message: it pushes the recipients, subject, bodies, template names and vars, headers and attachment paths as plain JSON to the `queue.yml` connection `app.email.queueConnection` (default `default`), on the channel `app.email.queueName` (default `default`). `php taphra queue:work` rebuilds the email with `Email::processQueue()` and sends it with the app's transport. The data is signed with the app key (`APP_SECRET_KEY` in `.env`, which `composer create-project` and `php taphra key:generate` write) and the worker refuses a job without the signature; without an app key, `queue()` and the worker refuse every email and say to set `APP_SECRET_KEY`. The worker also treats the data as untrusted: template, layout and theme names must stay inside the email folders, headers may not contain line breaks, and attachments must be files in the attachments folder. A send that fails throws, so the worker retries it. The attachments folder is `app/tmp/attachments` unless `app.email.attachments_path` in `app.yml` names another folder inside the app (relative to `app/`, or absolute). Write the files a queued email attaches there, and keep them until the worker has sent it. A file outside that folder, a `.env` file, or a folder that is not inside the app is refused; `send()` without the queue attaches any file you give it. ```yaml all: email: attachments_path: Storage/mail # app/Storage/mail ``` ## Catching mail in development In development you want to see each message without sending it. Two ways: - Run a local SMTP catcher such as Mailpit or MailHog and point the `dev` SMTP settings at it (`host: 127.0.0.1`, `port: 1025`, no `secure`, no username). Its web page shows every message. - Use the `sendmail` transport with a script that saves each message to a file. Nothing to install: ```bash #!/bin/sh # bin/catch-mail: saves each message it receives as app/tmp/mail-
_ $schema->dropColumn('notes', 'rank'); $schema->drop('notes'); ``` Column types: `id`, `string`, `char`, `text`, `mediumText`, `longText`, `integer`, `bigInteger`, `tinyInteger`, `boolean`, `float`, `double`, `decimal`, `date`, `time`, `dateTime`, `timestamp`, `json`, `jsonb`, `uuid`, `enum`, `binary`, `vector` (pgvector), `tsvector`, plus `timestamps()` and `softDeletes()`. Modifiers: `nullable()`, `default()`, `unique()`, `index()`, `primary()`, `unsigned()` (MySQL), `comment()` (MySQL), `generatedAs()`. Foreign keys are declared inside `create()`, which works on every driver, SQLite included: ```php $schema->create('comments', function ($t) { $t->id(); $t->integer('post_id'); $t->text('body'); $t->foreign('post_id', 'posts', 'id', 'CASCADE'); // ON DELETE CASCADE ON UPDATE RESTRICT }); ``` SQLite enforces them only on a connection with `PRAGMA foreign_keys = ON`: add `'extra' => ['pragma.foreign_keys' => 'ON']` to the connection's settings to have it run on every new connection. Also: `modifyColumn()` (not SQLite), `addForeignKey()` (an existing table; not SQLite), `ginIndex()`, `createExtension()` and `vectorIndex()` (PostgreSQL), and the `where:` (partial index), `using:` and `opclass:` arguments of `addIndex()`. --- ## Query log ```php use Taphra\QueryLog; QueryLog::enable(); PostDataStore::where('status', 'published')->get(); QueryLog::all(); // [['sql' => 'SELECT ...', 'duration_ms' => 0.1, 'trace' => null], ...] QueryLog::stats(); // count, total_ms, max_ms, slow_count QueryLog::disable(); QueryLog::reset(); ``` --- ## Exceptions | Class | Thrown by | |---|---| | `Taphra\Db\DbException` | connections, `SqlQuery`, adapters, `SchemaBuilder`: SQL errors, invalid names or operators | | `Taphra\Db\DataStoreException` | `DataStore`, `DataStoreCollection`, the query builder | | `Taphra\Db\RecordNotFoundException` | `DataStore::findOrFail()` (extends `DataStoreException`) | All of them extend `\RuntimeException`. --- Source: https://taphra.dev/docs/packages/validator/ # taphra/validator Input validator for PHP with string rules such as `required|email|max:255`. One class, no Composer dependencies; it needs only the `mbstring` extension. ## Requirements - PHP 8.2+ - `ext-mbstring` ## Installation ```bash composer require taphra/validator ``` ## Quick start ```php use Taphra\Validator; $input = [ 'email' => 'alice@example.com', 'age' => '17', 'role' => 'admin', 'password' => 'hunter2', 'confirm' => 'hunter2', 'slug' => 'hello-world', ]; $v = Validator::make($input, [ 'email' => 'required|email', 'age' => 'required|integer|min:18|max:120', 'role' => 'required|in:admin,editor,viewer', 'password' => 'required|min:8', 'confirm' => 'required|confirmed:password', 'slug' => 'regex:/^[a-z0-9-]+$/', ]); if ($v->fails()) { print_r($v->errors()); // [ // 'age' => ['The age must be at least 18.'], // 'password' => ['The password must be at least 8.'], // ] } ``` ## Built-in rules | Rule | Passes when | Example | |---|---|---| | `required` | the field is present and not null, `''` or `[]` | `required` | | `nullable` | always; when the field is null or `''` the remaining rules are skipped | `nullable\|email` | | `sometimes` | always; when the field is absent the remaining rules are skipped | `sometimes\|required` | | `email` | the value is an email address | `email` | | `url` | the value is a URL with an allowed scheme (see below) | `url`, `url:https` | | `integer` | the value is an integer or an integer string | `integer` | | `numeric` | the value is a number or a numeric string | `numeric` | | `boolean` | the value is `true`, `false`, `0`, `1`, `"0"`, `"1"`, `"true"` or `"false"` | `boolean` | | `alpha` | the value has ASCII letters only | `alpha` | | `alpha_num` | the value has ASCII letters and digits only | `alpha_num` | | `date` | `strtotime()` can parse the value | `date` | | `json` | the value is valid JSON | `json` | | `min` | the size is at least the parameter (see below) | `min:8` | | `max` | the size is at most the parameter (see below) | `max:255` | | `min_digits` | the value has at least N digit characters | `min_digits:6` | | `max_digits` | the value has at most N digit characters | `max_digits:10` | | `in` | the value is one of the listed values | `in:admin,editor,viewer` | | `not_in` | the value is none of the listed values | `not_in:banned,suspended` | | `confirmed` | the value equals another field (default: `_confirmation`) | `confirmed:password` | | `regex` | the value matches the pattern | `regex:/^[a-z]+$/` | | `starts_with` | the value starts with the parameter | `starts_with:https` | | `ends_with` | the value ends with the parameter | `ends_with:.com` | | `phone` | the value has between 7 and 15 digits (or the given range) | `phone`, `phone:10,10` | | `domain` | the value is a domain name | `domain` | | `unique` | no row in the given table has the value (see below) | `unique:main,users,email` | Rules other than `required`, `nullable` and `sometimes` are skipped when the field is null or `''`. ### How `min` and `max` measure - A number (an `int` or `float` value) is compared by value. - A numeric string is compared by value only when the field also has the `integer` or `numeric` rule: `integer|min:18` rejects `"17"`. - Any other string is compared by its length in characters: `min:8` rejects `"99"`. - An array is compared by its number of elements. ### Arrays An array value fails every rule that expects a single value (`email`, `url`, `in`, `regex`, `integer`, and so on). `required`, `min`, `max`, `confirmed` and custom rules receive the array as it is. ### URLs `url` accepts `http`, `https` and `ftp` URLs. Anything else fails, including `javascript:`, `data:`, `vbscript:` and `file:`. List the schemes you want to allow to change that: ```php 'website' => 'url:https', // https only 'link' => 'url:http,https,mailto', // also mailto: ``` ### Unknown rules A rule name that is neither built in nor registered with `Validator::extend()` throws an `InvalidArgumentException` naming the rule and the field, even when the field is empty. A typo such as `emial` therefore fails loudly instead of letting every value through. Rules in a pipe string are split on `|`. A regular expression that contains `|` must be given in array form: ```php 'code' => ['required', 'regex:/^(abc|def)$/'], ``` ## Result API ```php $v = Validator::make($data, $rules)->validate(); $v->passes(); // true when every rule passed $v->fails(); // true when any rule failed $v->errors(); // array: error messages per field $v->firstError('email'); // first error for a field, or null ``` `validate()` runs once; calling it again, or calling `passes()`, `fails()` or `errors()`, reuses the result. Messages name a field by its input name. `attributes()` gives fields readable names for every message, built-in or custom (`:field`); `errors()` stays keyed by the input name: ```php $v = Validator::make(['rate_limit_per_minute' => '0'], ['rate_limit_per_minute' => 'integer|min:1']) ->attributes(['rate_limit_per_minute' => 'rate limit']); $v->errors(); // ['rate_limit_per_minute' => ['The rate limit must be at least 1.']] ``` ## Custom rules ```php Validator::extend( 'even', function (string $field, mixed $value, array $params, array $data): bool { return is_numeric($value) && ((int) $value % 2 === 0); }, ':field must be an even number' ); // Error templates support :field, :param0, :param1, ... Validator::extend('between', function ($field, $value, $params) { return $value >= $params[0] && $value <= $params[1]; }, ':field must be between :param0 and :param1'); $v = Validator::make(['n' => '7'], ['n' => 'even|between:1,5']); $v->errors(); // ['n' => ['n must be an even number', 'n must be between 1 and 5']] ``` A custom rule cannot replace a built-in rule of the same name. ## Pipe and array syntax Both forms are equivalent: ```php $rules = ['email' => 'required|email']; $rules = ['email' => ['required', 'email']]; ``` ## The `unique` rule `unique` checks that no row in a table already has the value: ``` 'email' => 'unique:connection_name,table,column' 'email' => 'unique:connection_name,table,column,except_column,except_value' ``` The second form ignores the row where `except_column` equals `except_value` (for example the record being edited). Table and column names must be plain identifiers (letters, digits and `_`; the table may be `schema.table`); anything else throws an `InvalidArgumentException`. The value is always sent as a bound parameter. Inside the Taphra framework the database is wired for you. Standalone, register a resolver that returns a connection for the name in the rule: ```php Validator::setDatabaseResolver(function (string $connection): PDO { return new PDO('sqlite:/path/to/app.db'); }); $v = Validator::make(['email' => 'taken@example.com'], ['email' => 'unique:main,users,email']); $v->firstError('email'); // "The email has already been taken." ``` The resolver may return: - a `PDO` (identifiers are quoted for its driver), - a Taphra `DatabaseConnection` (`taphra/db`), - any object with `query(string $sql, array $bindings): array` that returns rows with a `cnt` column. If it also has `quoteIdentifier(string $name): string`, that is used to quote names; otherwise MySQL backticks are used. Without a resolver the rule throws a `LogicException`, and database errors are not caught: a uniqueness check that cannot run never reports success. ## `nullable` and `sometimes` ```php // nullable: skip the other rules when the field is empty (optional fields) $rules = ['bio' => 'nullable|max:500']; // sometimes: only validate the field when it is present in the input $rules = ['legacy_field' => 'sometimes|required|integer']; ``` ## Package layout ``` packages/validator/ composer.json src/ Validator.php # Taphra\Validator, a single class ``` --- Source: https://taphra.dev/docs/packages/container/ # taphra/container PSR-11 service container and `ServiceProvider` base class for Taphra. It is a standalone package: it does not depend on the `taphra/taphra` framework and works in any PHP 8.2+ project. ## Requirements - PHP >= 8.2 - `psr/container` ^2.0 ## Installation ```bash composer require taphra/container ``` ## Container `Taphra\Container\Container` implements `Psr\Container\ContainerInterface`. Every binding is a singleton: the factory runs on the first `get()` and the result is reused after that, even when it is `null`. ```php use Taphra\Container\Container; $c = new Container(); // Bind a factory (receives the container as its argument) $c->bind('mailer', fn($c) => new Mailer($c->get('config'))); $c->bind(\Psr\Log\LoggerInterface::class, fn($c) => $c->get('logger')); // Register a pre-resolved value $c->instance('db', $existingConnection); // Resolve $mailer = $c->get('mailer'); // factory called once; result cached $c->has('mailer'); // true // Re-binding replaces the cached instance $c->bind('mailer', fn($c) => new MockMailer()); // bind() and instance() return the container, so calls can be chained $c->instance('config', ['dsn' => 'smtp://localhost']) ->bind('clock', fn() => new DateTimeImmutable()); ``` **Exceptions:** - `Taphra\Container\NotFoundException` (implements `Psr\Container\NotFoundExceptionInterface`): no binding or instance exists for the ID. - `Taphra\Container\ContainerException` (implements `Psr\Container\ContainerExceptionInterface`): a factory threw; the original exception is available from `getPrevious()`. ## ServiceProvider `Taphra\ServiceProvider` is an abstract base class for grouping the bindings of one feature. ```php use Taphra\Container\Container; use Taphra\ServiceProvider; class MailerServiceProvider extends ServiceProvider { public function register(): void { // Bind only here; do not call $this->app->get() $this->app->bind(Mailer::class, fn($c) => new Mailer($c->get('config')['dsn'])); } public function boot(): void { // Safe to resolve here: every provider has run register() $this->app->get(Mailer::class)->setDefaultFrom('noreply@example.com'); } } ``` Providers run in two phases: 1. `register()` on every provider: bind services, never resolve them. 2. `boot()` on every provider, after all `register()` calls: resolving is safe. The default `boot()` does nothing. `$this->app` is the `Container` passed to the constructor. Without the framework, run the phases yourself: ```php $c = new Container(); $c->instance('config', ['dsn' => 'smtp://localhost']); $providers = [new MailerServiceProvider($c) /* , ... */]; foreach ($providers as $p) { $p->register(); } foreach ($providers as $p) { $p->boot(); } ``` ## Used by Taphra Core `taphra/taphra` depends on this package. The framework wires its own services in `Taphra\Container\TaphraContainerFactory`, which lives in the framework because it refers to framework classes (logger, router, HTTP layer). In a Taphra app, `Taphra\ProviderLoader` finds the providers in `app/Providers/` and those listed under `app.providers` in `app/Config/app.yml`, and runs both phases for you. ## Package Layout ``` packages/container/ composer.json src/ Container/ Container.php # PSR-11 container ContainerException.php # Psr\Container\ContainerExceptionInterface NotFoundException.php # Psr\Container\NotFoundExceptionInterface ServiceProvider.php # Abstract base (namespace Taphra\) ``` --- Source: https://taphra.dev/docs/packages/crypt/ # taphra/crypt Authenticated encryption for PHP with [libsodium](https://doc.libsodium.org/) secretbox (XSalsa20-Poly1305). One class, no Composer dependencies; it needs only the `sodium` extension, which PHP bundles. ## Requirements - PHP 8.2+ - `ext-sodium` ## Installation ```bash composer require taphra/crypt ``` ## Encrypting with a secret key Use `encrypt()` and `decrypt()` with a random key of at least 32 bytes, kept out of your code (for example in an environment variable). Generate one with: ```bash php -r 'echo bin2hex(random_bytes(32)), "\n";' ``` Inside a Taphra app, `php taphra key:generate` writes such a key to `.env` as `APP_SECRET_KEY`. ```php use Taphra\Crypt; $key = getenv('APP_SECRET_KEY'); // 64 hex characters $token = Crypt::encrypt('sensitive data', $key); // base64 text, different on every call $plain = Crypt::decrypt($token, $key); if ($plain === false) { // wrong key, truncated or tampered data } ``` ### `Crypt::encrypt(string $plaintext, string $key): string` Returns base64 text holding a format marker, a random 16-byte salt, a random 24-byte nonce and the ciphertext with its Poly1305 tag. The salt derives a fresh key for each message from yours (keyed BLAKE2b). The output is 60 bytes longer than the plaintext before base64 encoding. A key shorter than 32 bytes, including an empty one, throws an `InvalidArgumentException`. The length check cannot tell a random key from a long guessable one: use random bytes. ### `Crypt::decrypt(string $ciphertext, string $key): string|false` Returns the plaintext, or `false` when the key is wrong or the data was truncated or changed. It never returns partly decrypted data. `decrypt()` also reads ciphertexts written by earlier versions of this package, which used an unsalted BLAKE2b hash of the key and accepted keys of any length. Decrypt such data with its old key and encrypt it again with a strong one: ```php $plain = Crypt::decrypt($oldToken, $oldShortKey); $token = Crypt::encrypt($plain, $newKey); ``` ## Encrypting with a passphrase When the secret is something a person types, use the passphrase methods. They derive the key with Argon2id (`sodium_crypto_pwhash`) and a random salt stored in the output, which makes guessing the passphrase slow. ```php $token = Crypt::encryptWithPassphrase('notes', 'correct horse battery staple'); $plain = Crypt::decryptWithPassphrase($token, 'correct horse battery staple'); // "notes" Crypt::decryptWithPassphrase($token, 'wrong guess'); // false ``` Each call uses about 64 MB of memory and takes up to about a tenth of a second, so use them for a few values, not for bulk data. An empty passphrase throws an `InvalidArgumentException`. `decrypt()` and `decryptWithPassphrase()` never accept each other's output. ## Security properties | Property | Detail | |---|---| | Cipher | XSalsa20-Poly1305 (`sodium_crypto_secretbox`) | | Key from a secret key | keyed BLAKE2b over a random 16-byte salt per message; key at least 32 bytes | | Key from a passphrase | Argon2id, libsodium "interactive" cost, random 16-byte salt per message | | Nonce | 24 random bytes per message | | Integrity | Poly1305 tag: changed data returns `false` | | Memory | derived keys are wiped with `sodium_memzero()` after use | ## Package layout ``` packages/crypt/ composer.json src/ Crypt.php # Taphra\Crypt, static methods only ``` --- Source: https://taphra.dev/docs/packages/l10n/ # taphra/l10n Localisation for PHP. Messages are named by dot-notation keys or by their source text (gettext style). ICU MessageFormat (plural, select, number) is formatted by PHP's `intl` extension when it is loaded and by a built-in subset when it is not. Translations are YAML files, cached as PHP arrays. --- ## Requirements - PHP 8.2+ - `symfony/yaml` ^7.0 - `ext-intl` (optional): full CLDR plural rules, digits and number formats --- ## Installation ```bash composer require taphra/l10n ``` --- ## Standalone bootstrap When using `taphra/l10n` without the full Taphra framework, call `L10n::configure()` once before any translation calls: ```php use Taphra\L10n; L10n::configure([ 'locale' => 'fr', 'fallback_locale' => 'en', 'translations_path' => '/path/to/Translations', 'cache_path' => '/path/to/lang_cache', // optional; omit to disable caching ]); echo L10n::tr('auth.login'); // "Connexion" echo L10n::tr('welcome', ['name' => 'Alice']); // "Bonjour, Alice !" echo L10n::tr('messages.inbox', ['count' => 3]); // "3 messages" ``` with `fr.yml`: ```yaml welcome: "Bonjour, {name} !" auth: login: Connexion messages: inbox: "{count, plural, one{# message} other{# messages}}" ``` Every key in the config array is optional; only the keys present are applied. Individual setters are also available: ```php L10n::setTranslationsPath('/path/to/Translations'); L10n::setCachePath('/tmp/lang_cache'); L10n::setLocale('fr'); L10n::setFallbackLocale('en'); ``` Inside the Taphra framework these paths are wired automatically from `app.yml`. No setup is needed beyond setting the locale in config. --- ## Translation files Store one file per locale in your `Translations/` directory: ``` app/Translations/ en.yml fr.yml fr_CA.yml de.yml ``` Files are parsed by `symfony/yaml`. Keys can be nested to any depth: ```yaml # Translations/en.yml welcome: "Welcome, {name}!" auth: login: Sign in errors: invalid: Invalid email or password. messages: inbox: "You have {count, plural, one{# message} other{# messages}}." ``` Nested keys are flattened to dot-notation on load: `auth.errors.invalid`, `messages.inbox`. --- ## API ### `L10n::tr(string $key, array $replace = [], ?string $context = null): string` Translate a dot-notation key or a source text. When no catalog has it, the key itself is the message, formatted with `$replace` like a translated one (placeholders, plurals). ```php L10n::tr('auth.login'); // "Sign in" L10n::tr('welcome', ['name' => 'Alice']); // "Welcome, Alice!" L10n::tr('messages.inbox', ['count' => 3]); // "You have 3 messages." L10n::tr('missing.key'); // "missing.key" L10n::tr('{n, plural, one {# row} other {# rows}}', ['n' => 1234]); // "1,234 rows", with no catalog L10n::tr('Done', [], 'status'); // the "_context.status.Done" entry ``` ### Source text as the key Name a message by its text in the source language: views stay readable, the source language needs no catalog, and a message a catalog lacks falls back to the source text, formatted. ```yaml # fr.yml "Find more": "Trouver plus" "{count, plural, one {# row} other {# rows}}": "{count, plural, one {# ligne} other {# lignes}}" _context: status: "Done": "Terminé" # L10n::tr('Done', [], 'status') ``` ```php L10n::setSourceLocale('en'); // English misses are the message itself: not reported to the logger L10n::setLocale('fr'); L10n::tr('Find more'); // "Trouver plus" ``` `L10n::placeholders($message)` lists a message's argument names (branches included) so a test can check that each translation uses the same ones as its source; `L10n::pluralBranches($message)` and `L10n::pluralCategories($locale)` check its plural branches against the language's CLDR categories. ### `L10n::format(string $message, array $args = [], ?string $locale = null): string` Format a message without looking it up. ### `L10n::has(string $key, ?string $locale = null, ?string $context = null): bool` Check whether a key exists (follows the full fallback chain). ```php L10n::has('auth.login'); // true L10n::has('auth.login', 'fr'); // true if fr.yml, or the fallback locale's file, has that key ``` ### `L10n::catalog(?string $locale = null): array` Return the complete flat catalog for a locale (useful for debugging). ```php $all = L10n::catalog('en'); // ['auth.login' => 'Sign in', 'auth.errors.invalid' => '...', ...] ``` ### `L10n::number(float $number, int $decimals = 0): string` Format a number with the active locale's CLDR conventions (`intl`'s NumberFormatter when loaded, halves rounded up as `number_format()` does), else its decimal and thousands separators. ```php L10n::setLocale('en'); L10n::number(1234567.89, 2); // "1,234,567.89" L10n::setLocale('de'); L10n::number(1234567.89, 2); // "1.234.567,89" L10n::setLocale('fr'); L10n::number(1234567.89, 2); // "1 234 567,89" (narrow no-break spaces) ``` ### `L10n::setLocale(string $locale): void` ### `L10n::locale(): string` BCP 47 dash form (`fr-CA`) and underscore form (`fr_CA`) are both accepted; the locale is stored in underscore form. A locale set before the first lookup stays when the framework's configured locale is read (that one becomes the fallback). ### Locale format and `L10n::isValidLocale(string $locale): bool` A locale names files on disk (`fr_CA.yml`, `fr_CA.php`), so every method that takes one checks its shape first: a 2 or 3 letter language code, then optional subtags of up to 8 letters or digits, joined by `_` or `-` (`en`, `fil`, `pt-BR`, `zh_Hant_TW`, `de_DE_1901`, `ar-u-nu-latn`). `setLocale()`, `setFallbackLocale()`, `setSourceLocale()`, `has()`, `catalog()`, `format()` and `pluralCategories()` throw an `InvalidArgumentException` for anything else (`../x`, `en.UTF-8`, `e`), and the active locale stays as it was. A malformed locale in the configuration resolver is ignored. Check user input with `isValidLocale()` before passing it on: ```php $lang = $_GET['lang'] ?? 'en'; L10n::setLocale(L10n::isValidLocale($lang) ? $lang : 'en'); ``` Inside the framework, `LocaleMiddleware` picks the locale from the query string, a cookie or `Accept-Language`. ### `L10n::setSourceLocale(?string $locale): void` The language source texts are written in (also `source_locale` in `configure()` and the resolver's array). ### `L10n::useIntl(?bool $on): void` `false` forces the built-in formatter (tests, a host without `intl`); `null`, the default, uses `intl` when loaded. ### `L10n::setFallbackLocale(string $locale): void` ### `L10n::fallbackLocale(): string` ### `L10n::flatten(array $nested, string $prefix = ''): array` Utility to flatten a nested array to dot-notation keys. Called internally on YAML load; public for custom loaders. --- ## Locale fallback chain For a request locale of `fr_CA`: 1. `fr_CA.yml`: exact match 2. `fr.yml`: language-only parent 3. the fallback locale (default: `en`) Keys found in a more-specific locale take precedence over less-specific ones. --- ## Plural rules A message with an ICU `plural`, `select`, `selectordinal` or `number` argument is formatted as ICU MessageFormat: with `intl` loaded, by its `MessageFormatter` (every CLDR rule, the locale's digits, so `#` reads "1,234" in English, "1 234" in French and "١٬٢٣٤" in Arabic; `ar_MA` and `ar-u-nu-latn` write Latin digits); without it, by the built-in subset below (Latin digits). Any argument name works, not only `count`. In such a message an int or float value of a plain `{name}` is formatted as a number too (ICU's rule): pass a string to keep a year or an id as written. ICU reads an apostrophe right before a brace as a quote: write `’` there. ```yaml # en.yml items: "You have {count, plural, one{# item} other{# items}}." ``` ```php L10n::tr('items', ['count' => 1]); // "You have 1 item." L10n::tr('items', ['count' => 5]); // "You have 5 items." ``` **Exact-value overrides:** ```yaml items: "{count, plural, =0{none} one{# item} other{# items}}" ``` ```php L10n::tr('items', ['count' => 0]); // "none" ``` **Built-in subset: covered language families** (used without the `intl` extension): | Family | Languages | Categories | |---|---|---| | English-like | en, es, pt, nl, ... | one / other | | French-like | fr, pt_BR, ... | one (0 and 1 singular) / other | | Slavic | ru, uk, be, pl | one / few / many | | Czech/Slovak | cs, sk | one / few / other | | Romanian | ro | one / few / other | | Baltic | lt, lv | one / few / other (Latvian: zero) | | Arabic | ar | zero / one / two / few / many / other | | Welsh | cy | zero / one / two / few / many / other | | Irish | ga | one / two / few / many / other | | No plural | zh, ja, ko, tr, ... | other (always) | --- ## PHP-array cache On first load, the YAML file is parsed and written to a PHP-array cache file (`{locale}.php`) in the cache path. With OPcache enabled, later reads come from memory. A cache file older than its YAML file is rebuilt. Inside the framework, `php taphra optimize` builds every translation cache at deploy time. --- ## Missing-key logging ```php L10n::setLogger(function (string $message): void { error_log($message); }); // Logs: L10n: missing key "auth.missing" for locale "fr" ``` --- ## Package layout ``` packages/l10n/ composer.json src/ L10n.php # Taphra\L10n, a single static class ``` --- Source: https://taphra.dev/docs/packages/ai/ # taphra/ai AI layer for PHP: one interface over Anthropic, OpenAI, Ollama and OpenAI-compatible servers, with streaming, conversations, embeddings, structured output, a tool-use agent loop and an MCP server. It has no dependency on the Taphra framework; inside the framework it is configured from `app/Config/ai.yml`. --- ## Requirements - PHP 8.2+ - `ext-curl`, `ext-json` - `taphra/container`, installed with it (it holds `Taphra\TaphraExceptionInterface`, which every Taphra exception implements) - Optional: `psr/simple-cache` (or any PSR-16 cache) to use `CachedProvider` outside the framework --- ## Installation ```bash composer require taphra/ai ``` --- ## Quick start ```php use Taphra\Ai\AI; AI::configure([ 'default_provider' => 'anthropic', 'providers' => [ 'anthropic' => ['api_key' => '${ANTHROPIC_API_KEY}', 'model' => 'claude-opus-5-5'], 'openai' => ['api_key' => '${OPENAI_API_KEY}', 'model' => 'gpt-4o'], 'ollama' => ['base_url' => 'http://localhost:11434', 'model' => 'llama3'], ], ]); $reply = AI::complete([['role' => 'user', 'content' => 'Hello']]); echo $reply['content']; $gpt = AI::provider('openai'); ``` `${ENV_VAR}` placeholders are resolved from the environment when the config is read. For another config source (a secrets manager, a database) register a resolver instead: ```php use Taphra\Ai\AiConfig; AiConfig::setConfigResolver(fn() => MySecrets::get('ai')); ``` Inside the Taphra framework the same array lives in `app/Config/ai.yml` and is wired at boot, so `AI::configure()` is not needed. --- ## Providers You can also build providers directly. The config keys below can be set in the constructor array (or `ai.yml`) and most can be overridden per call in the `$options` argument of `complete()` and `stream()`. ```php use Taphra\Ai\AnthropicProvider; use Taphra\Ai\OpenAiProvider; use Taphra\Ai\OllamaProvider; $anthropic = new AnthropicProvider(['api_key' => getenv('ANTHROPIC_API_KEY')]); // model defaults to claude-opus-5-5 $gpt = new OpenAiProvider(['api_key' => getenv('OPENAI_API_KEY'), 'model' => 'gpt-4o']); $local = new OllamaProvider(['model' => 'llama3']); // http://localhost:11434 by default ``` | Provider | Default model | Config keys | |---|---|---| | `AnthropicProvider` | `claude-opus-5-5` | `api_key`, `base_url`, `model`, `max_tokens`, `temperature`, `top_p`, `top_k`, `thinking`, `effort` (low, medium, high, xhigh, max), `betas`, `api_version`, `structured_output` (`output_format` or `tool`), `max_continuations`, `voyage_api_key` (embeddings) | | `OpenAiProvider` | `gpt-4o` | `api_key`, `base_url`, `model`, `max_tokens`, `temperature`, `top_p`, `effort`, `strict`, `store`, `api`, `reasoning_model` | | `OllamaProvider` | `llama3` | `base_url`, `model`, `max_tokens`, `temperature`, `think`, `keep_alive` | All providers also take `timeout` (seconds, default 120), `stream_timeout` (default 600) and `transport` (see below). Settings a model does not accept are not sent. Anthropic models from Opus 4.7 on reject `temperature`, `top_p` and `top_k`, so those are dropped for them. OpenAI reasoning models (the o-series, GPT-5 and later) get `max_completion_tokens` or `max_output_tokens` and the reasoning effort, and no sampling settings; earlier models get `max_tokens`, `temperature` and `top_p`. ### OpenAI: Responses API or Chat Completions `OpenAiProvider` talks to either OpenAI API: - the Responses API (`/v1/responses`) for reasoning models on `api.openai.com`; - Chat Completions (`/v1/chat/completions`) for earlier models and for every other `base_url`, since OpenAI-compatible servers implement that one. Force one with `'api' => 'responses'` or `'api' => 'chat'` in the config or per call. If a model id is not recognised, set `'reasoning_model' => true` or `false` to choose the parameter family yourself. ### Any OpenAI-compatible server ```php $compatible = new OpenAiProvider([ 'api_key' => getenv('MY_SERVER_KEY'), 'base_url' => 'http://localhost:8000/v1', // any server that implements Chat Completions 'model' => 'my-model', ]); ``` ### The response array `complete()` returns the same shape for every provider: ```php $r = $provider->complete([['role' => 'user', 'content' => 'Hello!']]); $r['content']; // the text answer $r['role']; // 'assistant' $r['tool_calls']; // [['id' => ..., 'name' => ..., 'input' => [...]], ...] $r['stop_reason']; // the provider's stop reason $r['usage']; // token counts, see below $r['raw']; // the provider's own response $r['native']; // the provider's copy of the turn, to send back unchanged (tool loops) $r['thinking']; // reasoning text, when the provider returns it $r['parsed']; // the decoded answer, when an output schema is set ``` `stream()` yields text chunks as they arrive, and `embed()` returns one vector for a string or a list of vectors for a list of strings. Anthropic embeddings go through Voyage AI (`voyage_api_key` or the `VOYAGE_API_KEY` environment variable). ```php foreach ($provider->stream([['role' => 'user', 'content' => 'Tell me a story']]) as $chunk) { echo $chunk; } $vector = AI::provider('openai')->embed('a sentence to embed'); ``` ### Usage fields `$r['usage']` has the same keys for every provider: | Key | Meaning | |---|---| | `input_tokens` | Input tokens as the provider reports them (Anthropic counts only uncached input here; OpenAI and Ollama count all input) | | `output_tokens` | Output tokens, reasoning included | | `cache_read_tokens` | Input tokens served from the prompt cache | | `cache_write_tokens` | Input tokens written to the prompt cache | | `uncached_input_tokens` | Input tokens billed at the base input rate | | `total_input_tokens` | All input tokens: uncached plus cache read plus cache write | | `reasoning_tokens` | The part of `output_tokens` spent on reasoning, when the provider reports it | | `server_tool_use` | Server tool calls by kind, for example `['web_search_requests' => 2]` | To price a call, multiply `uncached_input_tokens`, `cache_read_tokens`, `cache_write_tokens` and `output_tokens` by their rates and add the server tool calls. ### Transport Requests go through a `Taphra\Ai\Http\HttpTransport`. The default is `CurlTransport` (TLS verification on). Pass another one in the config as `'transport' => $transport` or with `withTransport()`, for example to add a proxy or a recording layer. `FakeTransport` replays queued responses without any network, which is what tests use: ```php use Taphra\Ai\Http\FakeTransport; $http = (new FakeTransport())->queueJson([ 'content' => [['type' => 'text', 'text' => 'Hi there']], 'stop_reason' => 'end_turn', 'usage' => ['input_tokens' => 5, 'output_tokens' => 3], ]); $provider = (new AnthropicProvider(['api_key' => 'test']))->withTransport($http); $provider->complete([['role' => 'user', 'content' => 'Hello']]); // ['content' => 'Hi there', ...] $http->lastRequest()->json(); // the exact body that was sent ``` A rate-limit answer (HTTP 429) is retried with exponential backoff; set `rate_limiting.retry_attempts` (default 3) and `rate_limiting.retry_base_delay_ms` (default 500) in the config. --- ## Provider modifiers Each returns a new provider and leaves the original unchanged: ```php $p = $provider->withTools([$weatherTool]); // AiTool objects or raw provider tool definitions $p = $provider->withOutputSchema($schema); // structured output $p = $provider->withTransport(new FakeTransport()); ``` A raw tool definition is sent to the provider as it is. Use it for server tools the provider runs itself, for example `['type' => 'web_search_20260209', 'name' => 'web_search']` on Anthropic or `['type' => 'web_search']` on the OpenAI Responses API. --- ## Conversations Multi-turn history with a pluggable store. The oldest messages are dropped when the history gets close to the token budget. ```php use Taphra\Ai\Conversation; $conv = new Conversation('chat-123', 'memory'); // backends: memory, or any registered name $conv->addSystemMessage('You are a helpful assistant.'); $conv->addUserMessage('What is the capital of France?'); $reply = $provider->complete($conv->getMessages()); $conv->addAssistantMessage($reply['content']); $conv->addImageMessage('What is in this photo?', 'https://example.com/photo.jpg'); $conv->estimatedTokens(); // rough token count $conv->clear(); ``` Inside the framework the `session` (the default) and `cache` backends are registered for you. Standalone, register your own store (any `ConversationStoreInterface`): ```php Conversation::registerBackend('redis', fn() => new MyRedisConversationStore()); ``` An unregistered backend name falls back to memory, which keeps the history for the current request only. --- ## Prompt templates ```php use Taphra\Ai\Prompt; class SummarisePrompt extends Prompt { public function system(): string { return 'You are a concise technical writer. Use {style} style.'; } public function user(): string { return 'Summarise: {text}'; } } $messages = (new SummarisePrompt()) ->with(['style' => 'bullet-point', 'text' => $document]) ->toMessages(); // [['role' => 'system', ...], ['role' => 'user', ...]] ``` Prompts can also live in files: `summarise.prompt.php` returns `new class extends Prompt { ... }` and `Prompt::load('summarise')` loads it. Set the folder with `Prompt::setPromptsPath('/path/to/prompts')`; inside the framework it is `app/Prompts`. --- ## Structured output ```php use Taphra\Ai\StructuredOutput; $person = StructuredOutput::from($provider) ->schema([ 'type' => 'object', 'properties' => ['name' => ['type' => 'string'], 'age' => ['type' => 'integer']], 'required' => ['name', 'age'], ]) ->extract([['role' => 'user', 'content' => 'Extract: Alice, aged 30']]); // ['name' => 'Alice', 'age' => 30] ``` The answer is decoded and checked against the schema. `AiStructuredOutputException` is thrown when the model declines, the answer is cut off, it is not JSON, or it does not match. --- ## Tool-use agent loop ```php use Taphra\Ai\AgentLoop; use Taphra\Ai\AiTool; class WeatherTool extends AiTool { public function name(): string { return 'get_weather'; } public function description(): string { return 'Get current weather for a city.'; } public function inputSchema(): array { return [ 'type' => 'object', 'properties' => ['city' => ['type' => 'string', 'description' => 'City name']], 'required' => ['city'], ]; } public function execute(array $params) { return ['city' => $params['city'], 'temp' => 18, 'condition' => 'Cloudy']; } } $agent = new AgentLoop($provider); $agent->registerTool(new WeatherTool()); $agent->addProviderTool(['type' => 'web_search_20260209', 'name' => 'web_search']); // optional server tool $agent->onToolCall(function (string $name, array $params, string $result): void { echo "Tool called: $name\n"; }); $agent->maxIterations(10); $response = $agent->run('What is the weather in Paris and London?'); echo $response['content']; ``` The loop stops when the model makes no more tool calls and returns the last response. A tool that throws, or a tool name the model invents, is reported back to the model as an error result. `AiMaxIterationsException` is thrown when the loop reaches the iteration limit. `history()` returns the conversation so far and `reset()` clears it. --- ## FallbackProvider Tries providers in order. An `AiException` moves on to the next provider; any other error is thrown at once. ```php use Taphra\Ai\FallbackProvider; $provider = new FallbackProvider([$anthropic, $gpt]); // or, with configured providers: AI::fallback('anthropic', 'openai') ``` --- ## CachedProvider Caches `complete()` answers. The key covers everything that changes the answer: the messages, the call's options, and the provider's class, model and other settings, output schema and tools (credentials are left out). `stream()` and `embed()` are not cached. ```php use Taphra\Ai\CachedProvider; // Any PSR-16 cache, for example symfony/cache: $cache = new \Symfony\Component\Cache\Psr16Cache(new \Symfony\Component\Cache\Adapter\FilesystemAdapter()); $provider = new CachedProvider($anthropic, 3600, $cache); // TTL in seconds; 0 keeps entries with no expiry $provider->complete($messages); // calls the API $provider->complete($messages); // served from the cache // With configured providers: $provider = AI::withCache('anthropic', 3600, $cache); ``` Without a cache argument, `CachedProvider` uses the Taphra framework cache when the framework is installed, and caches nothing when it is not. If the cache fails, the call goes to the provider. Errors from the provider are passed on and not cached. --- ## Request log Inside a Taphra app every API request adds one JSON line to `app/tmp/Log/ai.log`: the time, provider, URL, model, and the token usage or the error. Prompts and answers often hold personal data, so they are not written unless you ask for them: ```yaml # app/Config/ai.yml logging: enabled: true # the usage and error log (default true; false writes nothing) payloads: false # true adds each request and answer (default false) redact_fields: [api_key, authorization] # keys blanked in logged payloads ``` --- ## Config snapshots in tests `AiConfig::snapshot()` and `AiConfig::restore()` save and put back the loaded config and the resolver, so a test can change the config without leaking it into the next test: ```php $saved = AiConfig::snapshot(); AiConfig::restore(['config' => ['default_provider' => 'ollama'], 'resolver' => null]); // ... code that reads the AI config ... AiConfig::restore($saved); ``` `AiConfig::reset()` drops the loaded config so it is read again, and `AI::reset()` drops the cached provider instances. --- ## MCP server Expose tools, resources and prompts over the Model Context Protocol. Mark public methods with the attributes: ```php use Taphra\Ai\Mcp\McpTool; use Taphra\Ai\Mcp\McpResource; use Taphra\Ai\Mcp\McpPrompt; class OrdersMcp { #[McpTool(name: 'list_orders', description: 'List recent orders', inputSchema: ['type' => 'object', 'properties' => ['limit' => ['type' => 'integer']]])] public function listOrders(array $params): array { /* ... */ } #[McpResource(uri: 'orders://recent', name: 'Recent orders', description: 'The last 20 orders')] public function recentOrders(array $params): array { /* ... */ } #[McpPrompt(name: 'summarise_order', description: 'Summarise an order')] public function summariseOrder(array $params): array { /* ... */ } } ``` Standalone, build the server yourself: ```php use Taphra\Ai\Mcp\McpDiscovery; use Taphra\Ai\Mcp\McpStdioServer; $discovery = (new McpDiscovery())->discover(new OrdersMcp()); (new McpStdioServer($discovery))->serve(); // newline-delimited JSON-RPC on stdin and stdout ``` For HTTP, `McpHttpTransport` takes the request method, headers and body and returns the response to send. It refuses every request unless you pass an `authorize` callback, and it accepts an `Origin` header only from loopback origins or the `allowed_origins` you list. Inside the framework, put the methods on an `AppMcpController` subclass and run `php taphra mcp:serve` (stdio; `--list` prints what was discovered). `php taphra make:mcp Orders --from-datastore=OrderDataStore` scaffolds CRUD tools from a DataStore. --- ## Exceptions | Class | Thrown when | |---|---| | `AiException` | Base class for all AI errors (HTTP errors, invalid answers, connection errors) | | `AiRateLimitException` | The provider answered HTTP 429 after all retries | | `AiStructuredOutputException` | A structured answer was declined, cut off, not JSON, or did not match the schema | | `AiMaxIterationsException` | The agent loop reached its iteration limit | `AiToolNotFoundException` is available for your own tool lookups; the package does not throw it. --- ## Package layout ``` src/ AI.php, AiConfig.php facade and config ProviderInterface.php, AbstractProvider.php AnthropicProvider.php, OpenAiProvider.php, OllamaProvider.php FallbackProvider.php, CachedProvider.php AgentLoop.php, AiTool.php, ToolRegistry.php, Message.php, Usage.php Conversation.php, ConversationStoreInterface.php, MemoryConversationStore.php Prompt.php, StructuredOutput.php Ai*Exception.php Http/ HttpTransport, CurlTransport, FakeTransport, HttpRequest, HttpResponse Schema/ JSON Schema helpers and the structured answer check Stream/ SSE and NDJSON stream parsers Wire/ per-provider message and model rules Mcp/ attributes, discovery, McpServer, stdio and HTTP transports, session stores ``` --- Source: https://taphra.dev/docs/packages/billing/ # taphra/billing Provider-agnostic billing layer for PHP, built for the Taphra framework and usable without it. Version 1 ships with a Stripe provider and a null provider for tests. Adding another provider (Paddle, Braintree, ...) takes one class and a config entry, with no changes to application code. --- ## Requirements - PHP 8.2+, `ext-curl`, `ext-json` - `taphra/db` and `taphra/container` (installed with the package) - Optional: `symfony/console` for the `billing:*` commands, `symfony/yaml` (or `ext-yaml`) to read `billing.yml`, and a PSR-16 cache (`psr/simple-cache`) for webhook replay protection across requests - Stripe: no SDK needed; the provider calls the Stripe REST API over cURL The package works without the Taphra framework. The facade, the providers, the result objects, the DataStores and the webhook controller need only the packages above. Inside the framework, `BillingController` is a framework controller, events go to `Taphra\Event`, and the framework cache is used for webhook replay protection. --- ## Installation ```bash composer require taphra/billing ``` Add the service provider to `app/Config/app.yml`: ```yaml all: providers: - Taphra\Billing\BillingServiceProvider ``` Run the migration to create the billing tables: ```bash php taphra billing:migrate ``` --- ## Standalone bootstrap When using `taphra/billing` without the full Taphra framework, call `Billing::configure()` once before any billing operations: ```php use Taphra\Billing\Billing; Billing::configure([ 'default_provider' => 'stripe', 'providers' => [ 'stripe' => [ 'secret_key' => $_ENV['STRIPE_SECRET_KEY'], 'webhook_secret' => $_ENV['STRIPE_WEBHOOK_SECRET'], ], ], ]); $customer = Billing::createCustomer(['email' => 'alice@example.com']); ``` `${ENV_VAR}` placeholders in values are still resolved against `getenv()` / `$_ENV`. For more control, inject a pre-built manager directly: ```php Billing::setManager(new BillingManager($myConfig)); ``` --- ## Configuration (framework mode) Create `app/Config/billing.yml` and set your credentials through environment variables: ```yaml default_provider: stripe providers: stripe: driver: stripe secret_key: "${STRIPE_SECRET_KEY}" webhook_secret: "${STRIPE_WEBHOOK_SECRET}" # api_version: "2024-06-20" # optional: pin a Stripe API version # timeout: 30 # optional: cURL timeout in seconds # webhook_tolerance: 300 # optional: max age of a webhook timestamp in seconds ``` Only providers listed under `providers` can be used. Asking for any other name, for example one taken from a webhook URL, throws `BillingException` with the code `provider_not_configured`. Set the environment variables in your server config, `.env` file, or shell: ```bash STRIPE_SECRET_KEY=sk_live_... STRIPE_WEBHOOK_SECRET=whsec_... ``` Use `sk_test_*` keys in development and staging. --- ## Basic usage ### Static facade ```php use Taphra\Billing\Billing; // Customers $customer = Billing::createCustomer(['email' => 'alice@example.com', 'name' => 'Alice']); $customer = Billing::getCustomer('cus_xxx'); // Subscriptions $sub = Billing::createSubscription($customer->id, 'price_monthly'); $sub = Billing::createSubscription($customer->id, 'price_pro', ['trial_days' => 14]); $sub = Billing::cancelSubscription($sub->id); // cancels at period end $sub = Billing::cancelSubscription($sub->id, atPeriodEnd: false); // immediate // One-time charges (amount in the smallest currency unit, cents for USD) $charge = Billing::charge($customer->id, 2999, 'usd', ['description' => 'Add-on fee']); $refund = Billing::refund($charge->id); // full refund $refund = Billing::refund($charge->id, 1000); // partial refund ($10.00) // Payment methods $methods = Billing::listPaymentMethods($customer->id); Billing::attachPaymentMethod($customer->id, 'pm_xxx'); ``` ### Provider-specific access ```php // Explicitly name the provider (useful when you have more than one configured) $customer = Billing::provider('stripe')->createCustomer(['email' => 'bob@example.com']); // Hosted billing portal (Stripe only in version 1) $url = Billing::provider()->billingPortalUrl($customer->id, 'https://yourapp.com/account'); // Hosted checkout $url = Billing::provider()->checkoutUrl($customer->id, 'price_monthly', [ 'success_url' => 'https://yourapp.com/billing/success', 'cancel_url' => 'https://yourapp.com/billing/cancel', 'trial_days' => 14, ]); ``` --- ## Billable trait Apply the `Billable` trait to any DataStore-backed model to add billing capabilities directly on the model. ```php // app/DataStores/UserDataStore.php use Taphra\Billing\Billable; class UserDataStore extends DataStore { use Billable; public $connection = 'main'; public $objectName = 'users'; } ``` ```php $user = new UserDataStore(); $user->read($id); // the trait works on the DataStore's loaded record // Create or retrieve the Stripe customer for this user $customer = $user->createOrGetBillingCustomer(); // Subscribe $sub = $user->subscribe('price_monthly'); $sub = $user->subscribe('price_pro', ['trial_days' => 14]); // Check status $user->subscribed(); // bool: active or trialing $user->onTrial(); // bool $sub = $user->activeSubscription(); // raw billing_subscriptions row or null // Cancel $user->cancelSubscription(); // at period end (default) $user->cancelSubscription(atPeriodEnd: false); // immediately // Charge $charge = $user->charge(999, 'usd', ['description' => 'Extra feature']); // Payment methods $methods = $user->paymentMethods(); // PaymentMethodResult[] // Get the provider-assigned customer ID $customerId = $user->billingProviderId(); // e.g. "cus_xxx" ``` ### Overriding column names The trait reads `id`, `email`, and `name` by default. Override if your model uses different column names: ```php class UserDataStore extends DataStore { use Billable; protected function billableId(): int { return (int) $this->billableRow()['user_id']; } protected function billableEmail(): string { return (string) $this->billableRow()['contact_email']; } protected function billableName(): string { return (string) $this->billableRow()['full_name']; } } ``` ### The billing database connection The billing tables use `Billing::connection()`: the `connection` key of `billing.yml` when set, else the connection of the app's `AppDataStore` (`app_master` in the skeleton), else `main`. `billing:migrate` uses the same default. To use another connection for one model, override `billingConnectionName()`: ```php class UserDataStore extends DataStore { use Billable; protected function billingConnectionName(): string { return 'billing'; } } ``` --- ## Webhooks ### 1. Create the controller ```php // app/Controllers/BillingWebhookController.php namespace App\Controllers; use Taphra\Billing\BillingController; use Taphra\Billing\Results\WebhookEvent; class BillingWebhookController extends BillingController { public function webhook(?string $provider = null): string { return parent::webhook($provider); } protected function afterDispatch(WebhookEvent $event): void { // Optional: record the event, send an alert, ... } } ``` `webhook()` is the action the router calls: it reads the raw request body, verifies the signature, fires the normalised event, sets the HTTP status and `Content-Type: application/json`, and returns the JSON body. `handle()` does the same work and returns `['status' => int, 'body' => string]` without sending anything, for when you call it from your own code. ### 2. Register the route Add to `app/Config/routes.yml`: ```yaml POST: /billing/webhook: BillingWebhook/webhook /billing/webhook/:provider: BillingWebhook/webhook ``` With the second route the provider name comes from the URL; it must be one of the providers in your billing config, otherwise the request gets a 400. ### 3. Listen for events The controller fires `Event::emit('billing.subscription.created', $event)` (or whichever normalised type matches) when the Taphra framework is installed. Register listeners anywhere; a ServiceProvider's `boot()` is the usual place: ```php use Taphra\Event; use Taphra\Billing\Results\WebhookEvent; use Taphra\Billing\Results\SubscriptionResult; Event::on('billing.subscription.created', function (WebhookEvent $event) { /** @var SubscriptionResult $sub */ $sub = $event->object; // activate features for $sub->customerId }); Event::on('billing.subscription.canceled', function (WebhookEvent $event) { // revoke access }); Event::on('billing.invoice.payment_failed', function (WebhookEvent $event) { // notify the user }); ``` Without the framework, override `afterDispatch()` to act on each event. ### How webhooks are checked - **Signature.** The `Stripe-Signature` header must carry a timestamp within `webhook_tolerance` seconds (300 by default) of the server clock and a `v1` signature made with your `webhook_secret`. While you roll a secret, Stripe sends one `v1` signature per active secret; the webhook is accepted when any of them matches. An empty `webhook_secret` refuses every webhook. - **Replays.** Each event id is accepted once for twice the tolerance plus a minute (11 minutes by default), which covers the whole time a captured request would still pass the timestamp check. A second delivery of the same event in that time gets a 200 with `{"received": true, "duplicate": true}` and is not dispatched again. If your listener throws, the event id is released so the provider's retry is accepted. Keep your listeners idempotent anyway: a provider can deliver an event again later than that. - **Where event ids are kept.** In the PSR-16 cache you give the provider, otherwise in the framework cache when the framework is installed, otherwise in memory for the life of the PHP process (which does not cover separate PHP-FPM requests). Outside the framework, set a cache: ```php Billing::provider('stripe')->setWebhookCache($psr16Cache); ``` - **The null provider** cannot verify signatures, so it accepts webhooks only while tests run (PHPUnit or Pest loaded, or `APP_ENV` set to `test` or `testing`). Anywhere else it throws. Set `allow_unsigned_webhooks: true` in its config to accept unsigned webhooks, for local development only. ### Normalised event types | Normalised (`billing.*`) | Stripe event | |--------------------------------------|---------------------------------------| | `billing.subscription.created` | `customer.subscription.created` | | `billing.subscription.updated` | `customer.subscription.updated` | | `billing.subscription.canceled` | `customer.subscription.deleted` | | `billing.subscription.trial_ending` | `customer.subscription.trial_will_end`| | `billing.charge.succeeded` | `payment_intent.succeeded` | | `billing.charge.failed` | `payment_intent.payment_failed` | | `billing.charge.refunded` | `charge.refunded` | | `billing.payment_method.attached` | `payment_method.attached` | | `billing.payment_method.detached` | `payment_method.detached` | | `billing.invoice.payment_succeeded` | `invoice.payment_succeeded` | | `billing.invoice.payment_failed` | `invoice.payment_failed` | | `billing.unknown` | *(any unmapped Stripe event)* | Print the full map at any time: ```bash php taphra billing:webhooks ``` --- ## Result objects All provider methods return immutable `readonly` value objects. Use `->toArray()` to serialize. ### `CustomerResult` ``` $res->id // "cus_xxx" $res->email $res->name $res->provider // "stripe" $res->raw // full provider response array ``` ### `SubscriptionResult` ``` $res->id $res->customerId $res->planId $res->status // active | trialing | past_due | canceled | incomplete | paused $res->currentPeriodStart // Unix timestamp or null $res->currentPeriodEnd // Unix timestamp or null $res->trialEnd // Unix timestamp or null $res->canceledAt // Unix timestamp or null $res->isActive() // true when active or trialing $res->onTrial() // true when trialing $res->isCanceled() ``` ### `ChargeResult` ``` $res->id $res->customerId $res->amount // in smallest unit (e.g. cents) $res->currency // "usd" $res->status // succeeded | pending | failed | refunded $res->description $res->createdAt // Unix timestamp $res->succeeded() $res->amountFormatted() // "9.99" ``` ### `PaymentMethodResult` ``` $res->id $res->customerId $res->type // "card" $res->last4 $res->brand // "visa", "mastercard", etc. $res->expMonth $res->expYear $res->isDefault $res->isExpired() ``` ### `WebhookEvent` ``` $event->id $event->type // normalised "billing.*" name $event->providerType // raw Stripe event name $event->object // SubscriptionResult | ChargeResult | PaymentMethodResult | null $event->raw // full provider payload $event->provider // "stripe" $event->createdAt // Unix timestamp ``` --- ## CLI commands The commands need `symfony/console`. `BillingServiceProvider::commands()` returns them, and the Taphra console lists the commands of every booted provider, so they appear once the provider is in `app.providers` (or in `app/Providers/`). ```bash # Create billing tables (run once after installation or after deploy to a new DB) php taphra billing:migrate php taphra billing:migrate --connection=billing # another connection from databases.yml # Re-sync subscription statuses from the provider (after webhook outage, initial import, etc.) php taphra billing:sync php taphra billing:sync --provider=stripe php taphra billing:sync --dry-run # preview without writing # Print the normalised event map with example listener code php taphra billing:webhooks ``` --- ## Testing Use `NullProvider` in tests: no HTTP calls, no API keys, deterministic stubs. Its `parseWebhook()` accepts any payload while tests run and refuses it anywhere else (see "How webhooks are checked"). ```php use Taphra\Billing\Billing; use Taphra\Billing\BillingManager; protected function setUp(): void { $manager = new BillingManager([ 'default_provider' => 'null', 'providers' => ['null' => ['driver' => 'null']], ]); Billing::setManager($manager); } protected function tearDown(): void { Billing::reset(); } public function testUserSubscribes(): void { $sub = Billing::createSubscription('cus_test', 'price_monthly'); $this->assertSame('active', $sub->status); } ``` --- ## Adding a new provider To add Paddle, Braintree, or any other processor: **1. Implement the interface:** ```php namespace App\Billing; use Taphra\Billing\AbstractBillingProvider; use Taphra\Billing\BillingProviderInterface; // ...implement all methods... class PaddleProvider extends AbstractBillingProvider { public function getName(): string { return 'paddle'; } // ... } ``` **2. Register it (choose one approach):** ```php // In a ServiceProvider boot(), explicit registration: Billing::extend('paddle', \App\Billing\PaddleProvider::class); ``` ```php // Or place the class at Taphra\Billing\Providers\PaddleProvider to have it resolved by convention. ``` **3. Add config** (a provider that is not listed under `providers` cannot be used): ```yaml # app/Config/billing.yml default_provider: paddle providers: paddle: driver: paddle vendor_id: "${PADDLE_VENDOR_ID}" vendor_auth_code: "${PADDLE_AUTH_CODE}" ``` Application code using `Billing::provider()`, the `Billable` trait and `Event::on('billing.*')` listeners does not change. Your provider's `parseWebhook()` must verify the provider's signature; `claimWebhookEvent()` and `releaseWebhookEvent()` from `AbstractBillingProvider` give you the same replay protection as the Stripe provider. --- ## Database tables ### `billing_customers` | Column | Type | Notes | |-----------------|---------------|------------------------------------------| | `id` | INT PK | | | `billable_type` | VARCHAR(150) | Owner class (e.g. `App\DataStores\UserDataStore`) | | `billable_id` | INT | Owner primary key | | `provider` | VARCHAR(50) | e.g. `stripe` | | `provider_id` | VARCHAR(100) | e.g. `cus_xxx` | | `email` | VARCHAR(255) | | | `name` | VARCHAR(255) | nullable | | `created_at` | DATETIME | | | `updated_at` | DATETIME | | ### `billing_subscriptions` | Column | Type | Notes | |------------------------|--------------|--------------------------------------------| | `id` | INT PK | | | `billing_customer_id` | INT | FK → `billing_customers.id` | | `provider` | VARCHAR(50) | e.g. `stripe` | | `provider_id` | VARCHAR(100) | e.g. `sub_xxx` | | `plan_id` | VARCHAR(100) | Price/plan ID at the provider | | `status` | VARCHAR(30) | `active` · `trialing` · `past_due` · `canceled` · `incomplete` · `paused` | | `trial_ends_at` | DATETIME | nullable | | `current_period_start` | DATETIME | nullable | | `current_period_end` | DATETIME | nullable | | `canceled_at` | DATETIME | nullable | | `created_at` | DATETIME | | | `updated_at` | DATETIME | |