Reference
Changelog
All notable changes to Taphra are documented in this file.
The format is based on Keep a Changelog, and this project follows Semantic Versioning.
A minor release with no breaking change; see the upgrade note for the new features and the few behaviours a user may notice.
Added
#- A Composer package can register its routes and controller namespace from its service provider with
Router::addPackageRoutes(), served on both entries, inroute:list, with frozen routes and in worker mode; the app's own routes keep priority, a package route can only target the controllers of its own namespace, and a route target of the app can name a controller by its full class name. (#18) - Migrations from more than one folder: a package adds its folder with
Migration::addPath(), an app lists its own underpathsinmigrations.yml; every migrate command covers all of them in ID order, each folder keeps its own state, and migration classes may declare a namespace. An app with one folder works as before. (#19) - Foreign keys inside
create():TableBlueprint::foreign()writes the constraint intoCREATE TABLEon SQLite, MySQL, PostgreSQL and SQL Server (MySQL rejectsSET DEFAULT, so it is refused there), andaddForeignKey()on SQLite says to use it. SQLite enforces foreign keys only when they are turned on:pragma.foreign_keys: ONin a connection'sextraruns the pragma on every new connection; Taphra does not turn it on by default. (#9) - HTML controllers can return a redirect and set headers that every entry and
HttpTestCasesee:return $this->seeOther($url)answers 303 withLocation(redirect()still ends the process), andController::header($name, $value)works asRestController::header()does. (#11) - Readable field names in validation messages:
Validator::make(...)->attributes(['rate_limit_per_minute' => 'rate limit'])and aFormRequest::attributes()method name fields in every message ("The rate limit must be at least 1.");errors()stays keyed by the input name, and without names the messages are unchanged. (#12) HttpTestCase::postRaw($path, $body, $contentType, $headers)andsendRaw($method, ...)send a raw body with its content type (a signed webhook payload, XML, a JSON list, malformed JSON) through the pipeline, andRequest::rawBody()returns the body of the request being handled on both entries, so an action reads it the same way in tests and in production. (#20)
Changed
#- The PSR-15 entry (
ActionDispatcherMiddleware) boots the service providers before routing, as the default entry already did, so providers run on its first request too and can add routes. (#18) Schedule::reset()is public API: it was marked@internalin 1.0.2. An app's tests call it insetUp()andtearDown()to start from an empty schedule, as the scheduler guide now shows. (#22)HttpTestCaseputs the request headers in$_SERVERwhile a request runs (soisHtmx(),Request::headers()and theX-CSRF-Tokencheck see them) and starts each request with status 200; thehtmxPushUrl(),htmxReswap(),htmxRetarget()andhtmxTriggerEvent()headers also reach the PSR-7 response. (#11)- The methods 1.1.0 adds to classes apps extend declare no native return type, so a subclass method of the same name with or without one keeps loading where its parameters are compatible; the upgrade note lists each with what such a method must match. A public controller action named
seeOtheris no longer reachable by URL. (#11, #12, #18, #19, #20)
Fixed
#Fixed
#- A response header set several times with different letter cases (
X-Probe, thenx-probe, thenX-Probe) reaches the PSR-7 response with the last value set, as with PHP'sheader(); the header collector ofRestController::header(),RestController::emitHeader()andController::header()kept one entry per spelling, so an older value could win. (#11) SchemaBuilder::addForeignKey()on SQL Server sendsNO ACTIONforRESTRICT, its default, which SQL Server does not accept; it used to fail there unless both actions were given. (#9)
A bug-fix release; see the upgrade note for the fixes a user may notice, among them one escaping workaround that must be removed.
Fixed
#- A view variable passed to an element is escaped once: the element used to escape the already escaped string again, so
O'Brien & Coshowed asO'Brien & Co. Every other string an element receives is still escaped. (#5) - An UPDATE given a list of rows (one run per row) binds the WHERE values on every run on PostgreSQL, SQLite, MySQL and SQL Server. Only the SET values were bound, so a bound condition failed with a parameter count error (PostgreSQL) or matched no row (SQLite). (#16)
DataStore::save($data)with an array serialises the casts and sets theTimestampscolumns, as saving the active record does: the array goes throughbeforeSave(), where the hooks see it in$this->activeRecord, and the loaded active record is no longer changed by it. (#15)- The framework's own tests can start from an empty schedule:
Schedule::reset(), marked@internal, forgets the process-wide schedule thatSchedule::command()andSchedule::call()add to. It is not part of the public API in 1.0. (#22) - The routing guide and the docblock of
Router::getRoutes()say what it returns: each pattern is the regular expression the router matches, with escaped slashes and expanded named parameters (\/p\/([^\/]+)\/connectors), andstr_replace('\/', '/', $pattern)gives the formroute:listprints. The return value is unchanged. (#21) - The four starters set
config.platform.phpto8.2.0incomposer.json, socomposer create-projecton PHP 8.4 writes a lock file that installs on PHP 8.2 and 8.3 too; it used to locksymfony/processandsymfony/string8.x, which need PHP 8.4. See Deployment to raise it. (#10) - A
beforeSave()hook that returnsfalsecancels the save without an error, as the docs say:save()returnsfalse(it threwTypeError: Return value must be of type mixed, none returned), andcreate()throwsTaphra\Db\DataStoreExceptioninstead of returning a row that was never written. (#23) fill()thensave()on a new DataStore that usesTimestampssetscreated_atas well asupdated_at, also withoutresetRecord()first: the hook was told it was an insert only afterresetRecord()or aread()that found nothing. (#24)
Changed
#- The four starters also ship a one-line
CLAUDE.mdthat loads theirAGENTS.md, for coding agents that read only a file of that name. The guide itself is unchanged and still lives inAGENTS.md.
A bug-fix release; see the upgrade note for the two fixes that change behaviour.
Fixed
#execute()on an SQL connection returns the number of rows the statement changed when it has parameters too; it used to add one per value row, so an UPDATE that matched nothing returned 1. A statement run once per value row now sums the rows of every run inaffectedRows(). (#2)DatabaseConnection::load()returns the connection the DataStores of that name share (it opened a new one on every call), so raw SQL on it insideDataStore::transaction()is part of the transaction, as the docs say; an in-memory SQLite database is now the same one for both. The database lock, queue and session drivers keep separate connections of their own. See the upgrade note. (#3)- An MCP endpoint can be tested with
HttpTestCase, as the MCP guide says: on the PSR-15 entryMcpControllerreads the headers and body of the request being dispatched, which it used to miss (every test request got 401 or 400). The standard entry still reads$_SERVERandphp://input. (#6) - A route group's
GET /entry is the group's own page (/inboxfor the prefix/inbox): group routes drop a trailing slash, which no request path has, so the entry used to never match. (#4) php taphra mcp:servedescribes the server with themcpServerOptions()of theMcpControllersubclasses it finds (title, instructions and the rest), as the HTTP endpoint does; it used to readapp.app_nameonly. (#7)- The
Timestampstrait'sbeforeSave()calls the parentbeforeSave(), so a DataStore that uses it serialises its casts on save again (anobjectcast failed with "Object of class stdClass could not be converted to string"), and a base class's hook runs. (#8) ErrorController::onError()is no longer reachable by URL: on an error controller,GET /appError/onErroranswers 404 instead of running the hook without its argument and logging a 500. Other controllers can still have an action namedonError. (#13)
Changed
#- The package descriptions on Packagist no longer contain long dashes.
The first public release.
Requirements: PHP 8.2, 8.3 or 8.4 (all three tested in CI) with the curl, json, mbstring, pdo and sodium extensions. Install the framework with composer require taphra/taphra, or start an app with composer create-project taphra/skeleton my-app (also taphra/api-starter, taphra/ai-chat and taphra/mcp-server).
Added
#- One installable package,
taphra/taphra, that includes seven libraries also published on their own:taphra/db,taphra/validator,taphra/container,taphra/crypt,taphra/l10n,taphra/aiandtaphra/billing. - Web layer: YAML routes with named parameters, named routes and route groups with PSR-15 middleware; controllers with views, layouts and elements; HTML and form helpers; Server-Sent Events and HTMX helpers; a
RestControllerand aCrudControllerfor JSON APIs, API resources and OpenAPI output (php taphra route:openapi). - Requests and validation: typed input accessors, a string-rule validator and form requests.
- Database: DataStores (one class per table) with a query builder, casts, relations and eager loading, scopes, global filters, hooks, observers, timestamps, soft deletes and pagination; SqlQuery for joins, CTEs, set operations, window functions, upserts and
RETURNING; a schema builder and migrations; seeders and factories. - Authentication: session and JWT drivers, remember-me cookies, password hashing, password reset and email verification tokens, TOTP two-factor codes with backup codes, policies.
- Application services: queues (Redis, database, Beanstalkd) with
queue:work, cache drivers and locks, events, a scheduler run from one cron entry, email over PHPMailer, localisation with ICU plural rules, billing with a Stripe provider and a null provider for tests. - AI: Anthropic, OpenAI and Ollama providers behind one interface. OpenAI uses the Responses API for reasoning models and Chat Completions otherwise, which also serves OpenAI-compatible servers. Token streaming, structured output (Ollama
format, OpenAI strict mode as an option, Anthropicoutput_config), a provider-neutral agent loop with tool use, thinking blocks kept across turns, server tools, usage figures with cache tokens, conversations, prompt templates,FallbackProviderforcomplete()andstream(),CachedProvider, andAiConfig::snapshot()/restore(). - MCP: a server that negotiates protocol versions 2025-11-25, 2025-06-18, 2025-03-26 and 2024-11-05; tools, resources and prompts declared with PHP attributes; a stdio transport (
php taphra mcp:serve) and a Streamable HTTP transport. - Operations:
php taphra optimize(compiled config and routes, an opcache preload script), FrankenPHP worker mode, request IDs in every log line, an opt-in request log withphp taphra debug:request, andphp taphra tinker. Taphra\Framework, the application singleton, withFramework::mode()andFramework::modeFromEnvironment(); the global classTaphrais an alias of it.Taphra\Helpers, the namespaced form of the template helpers (Helpers::e(),Helpers::url()and the others). Each global helper function is defined only when no function of that name exists yet, so an app or a library can define its owne(),dump()ordd().Taphra\TaphraExceptionInterface, implemented by every exception class of Taphra and its packages, so onecatchhandles any framework error.- The AI app builder,
php taphra ai:build,ai:fixandai:rollback, as a preview feature: it works, and its behaviour may still change in minor releases. It asks before every file write and before every command outside an exact allow-list, never runs a shell, and keeps a receipt so a session can be rolled back.
Changed
#For apps built on a pre-release copy of Taphra:
- The logging helpers are
tphr_log(),tphr_dbg(),tphr_warning(),tphr_notice()andtphr_err(). The session keys (_tphr_errors,_tphr_old,_tphr_user) and the remember-me cookie (_tphr_remember) use thetphr_prefix, so signed-in users sign in again once after the upgrade. The widget folder constant isTPHR_WIDGET_PATH, client components register onwindow.__TAPHRA_COMPONENTS__, and the request log isapp/tmp/Log/requests.log. - The skeleton turns on
routing.strict: a POST, PUT, PATCH or DELETE request needs a route that declares that method, and a GET never reaches an action that a POST route binds.make:crudand the other generators print routes in method sections. - The action cache serves anonymous GET and HEAD requests only, and its key includes the query string.
- Error pages are chosen per status (the app's
error<status>view, such aserror403orerror429, then a genericerrorview), and production JSON errors carry the status's own reason phrase. - An
.envfile at the app root is loaded at boot (real environment variables win), andapp.keyfalls back toAPP_SECRET_KEY. - With an app key set, queued email jobs carry a signature; jobs queued by a pre-release copy are refused. Queued email is plain data rebuilt by the worker.
- Queue payloads that are not strings are JSON-encoded on push and decoded on pull.
route:openapi --versionis now--api-version.- An unclosed quote in
.envstops the boot with an error that names the line. - Database calls that used to be accepted now throw or behave more strictly: a string under an integer key in a condition array throws, an array id must name exactly the primary key columns, and with
$fillableor$guardeddeclared a primary key insave($data)that is not fillable is dropped, so the call inserts. - The suggested JWT library is
firebase/php-jwt^6.11 or ^7.2. - AI structured output: the answer is checked against the whole JSON Schema (before, only the top-level required fields). Anthropic models from 4.1 on use
output_formatby default instead of a forced tool, and thetools-2024-04-04beta header is no longer sent (structured_output: toolkeeps the forced tool). OpenAI reasoning models go to the Responses API (api: chatkeeps Chat Completions).AiStructuredOutputExceptioncarries the provider's response and usage (response(),usage()), so a billed call whose answer fails the check can still be counted. - AI providers make their HTTP calls through
Taphra\Ai\Http\CurlTransport; replace it withwithTransport()(for exampleFakeTransportin tests) instead of overriding the providers' cURL code.
Removed
#- The
php taphra launchandphp taphra utilscommands. Themake:*generators,cache:clearandroute:listcover whatutilsdid.
Security
#These defaults apply from 1.0.0. If you are moving an app from a pre-release copy of Taphra, check each one; Upgrading says what to change.
- An unset or unknown
APP_ENVmeans production. The Whoops debug page is only used in development. FormRequest::validated()never returns input that failed its rules: it throwsValidationException(HTTP 422). A newstringrule rejects JSON numbers, booleans and lists where text is expected; the starters use it for passwords and other text fields.- JWTs are refused before their
nbf(not before) time. - Query-result cache entries are keyed by the database they came from (connection name, driver, host, port and database, never credentials) and by DataStore class, so two databases sharing a cache never see each other's rows.
- TOTP codes and billing webhook event ids are claimed with an atomic cache add (Redis SET NX, Memcache add, APCu add, an exclusive file lock), so two simultaneous requests cannot both use one code or run one event twice. A webhook whose id cannot be recorded gets a 500 so the provider retries. A failed handler releases its webhook claim with an atomic compare-and-delete, so it never removes a newer delivery's claim, and verifications of one TOTP secret run one at a time, so the last accepted step never moves backwards.
Auth::hashPassword()uses Argon2id when PHP supports it, otherwise bcrypt, and refuses passwords bcrypt would truncate (over 72 bytes) or that contain a NUL byte.- The cache reads values back with an allow list of classes (DataStore rows and collections,
DateTime,DateTimeImmutable), never with unrestrictedunserialize(). - The AI builder asks before running a
make:*generator, like any other file write. - Only the public methods an app's controllers declare are URL actions. The base class helpers (
sse(),redirect(),csrf(), thehtmx*()helpers and the others) are protected or otherwise not reachable from a URL.sse()takes a Generator or a Closure. - A request with the wrong HTTP method for a declared route gets 405 with an
Allowheader. - CSRF tokens are checked on every request that is not GET, HEAD or OPTIONS, and the skeleton turns the check on for its controllers.
- Session cookies are HttpOnly, SameSite=Lax and Secure over HTTPS, and sessions use strict mode.
X-Forwarded-ForandX-Forwarded-Protoare trusted only from the addresses inapp.trusted_proxies.url()builds absolute links frombase_urlin production, never from theHostheader.- Route group middleware runs whether a route is reached by its declared path or by its controller/action URL.
- Database values are always bound as parameters, and identifiers and operators are checked; raw SQL goes only through the
*Raw()methods.$fillableand$guardedare respected.findOrFail()throwsTaphra\Db\RecordNotFoundException, which the framework answers with 404. - Email bodies use
{{ name }}placeholders, escaped in HTML bodies, instead of running as PHP. - The HTML helpers escape attributes, option labels and anchor text (
SafeStringopts out), ande()does not escape a value twice. - The validator throws on an unknown rule,
minandmaxmeasure string length for strings, andurlaccepts only http, https and ftp. Cryptneeds 32-byte keys; passphrases have their own API. JWT secrets must be at least 32 bytes. TOTP verification fails closed when the cache is unavailable.- Queue workers only run classes that implement
Taphra\Queue\JobInterface. - The MCP HTTP transport refuses every request until a token is set or
authorizeMcp()is overridden, checks theOriginheader and requires JSON. - Worker mode resets per-request state between requests (
RequestState::reset()). - Production logs
noticeand above by default (app.logging.level), andlogging.method: nulldiscards log entries. JwtMiddlewareandJwtAuthaccept access tokens only (token_use: access). Tokens withouttoken_usestill work unless_type,typortypemarks them as refresh tokens, so refresh tokens from earliermake:authcontrollers ("_type": "refresh") are refused.- The AI builder no longer runs git (run it yourself), blocks wrappers that run another program (flock, tmux, screen, setarch and similar), more interpreters, and Windows scripts and shells (names are matched without
.exe), and refuses commands and paths that name.env,.gitor Windows short names such asGIT~1. With--dontaskforpermissionsonly Taphra commands and the file tools run.ai:build --continuekeeps asking before every command once earlier sessions wrote files, and approval prompts show every invisible Unicode character as a visible escape. - The opt-in request log writes cookies,
Authorization, and headers, query parameters and body fields named like a token, secret, key, password, pass, pw, otp, code, jwt, pin, session id or CSRF field as[redacted], redacts bodies it cannot parse and token-like path segments, and does not rewrite existing entries. - The action cache stores the status and the headers that say how to read the body (
Content-Type, CSP,X-Content-Type-Options,HX-*) and sends them again on a hit;Accept,Accept-Languageand the htmx headers are part of the key. $guardedmatches column names in any case, and keys that are not columns are dropped.firstOrCreate()andupdateOrCreate()filter their data through$fillableand$guarded.- Login and message limits in the starters and in
make:authuseRateLimiter::attempt(), which cannot be raced.Auth::verifyPassword()accepts null and checks a dummy hash, so login timing does not reveal which accounts exist. - The generated
AppRestControllerreadsJwtMiddleware::payload(), never request input. - Worker mode forgets the previous session id between requests.
- Queued email needs an app key and attaches only files from
app.email.attachments_path(defaultapp/tmp/attachments). - JSON error bodies show the exception message in development only.
- MCP tokens must be at least 32 bytes; the mcp-server starter writes one at
create-projectand exposes one endpoint. All four starters turn onrouting.strict. make:dockerfilepublishes the app on 127.0.0.1 only, publishes no database or Redis port, and keeps a randomDB_PASSWORDin.env.
Known limitations
#- MCP: the stateless 2026-07-28 protocol revision is not implemented (clients that speak both fall back to
initialize). The server answers requests only: no sampling, elicitation, resource subscriptions or list-changed notifications. The HTTP transport answers with JSON (no server-initiated SSE stream) and keeps sessions in files on one server. - Tool arguments are not checked against the tool's input schema, in the agent loop and in MCP
tools/call. Validate them in the tool. AI::stream()yields text only, and a streamed request is not retried on HTTP 429.- Queues have no delayed dispatch, a job that was running when its worker died is not retried, and
queue:failedonly prints a reminder. - The scheduler has no overlap protection.
- On the default entry (
app/Static/index.php), route middleware can stop a request and add headers, but cannot change the response body or status, and a JSON request body is not part ofRequest::input(). Routes are the same in every environment. - SQL Server support is generated SQL covered by unit tests of that SQL; it is not tested against a running server.
MongodbConnectionis experimental and not tested against a running server. DataStores on MongoDB are not supported: a condition that cannot be turned into a MongoDB filter is refused.- There is no WebSocket server. A Server-Sent Events stream holds a PHP worker for as long as it is open.
- The skeleton loads its own
*.class.phpfiles through a Composer classmap, so a class file you add with that suffix needscomposer dump-autoload. Files named<Class>.php, which themake:*commands write, load at once.