Documentation menu

Building an app

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.

Contents

#

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). 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) are not actions either.

Declaring routes

#

Declared routes give you clean URLs, HTTP methods and parameters. They live in app/Config/routes.yml:

app/Config/routes.yml
# 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+.

app/Controllers/PostController.php
<?php
// app/Controllers/PostController.php
namespace App\Controllers;

class PostController extends AppController
{
    public function index(): string
    {
        return 'All posts';
    }

    public function show(int $id): string
    {
        return "Post {$id}";
    }

    public function tag(string $slug): string
    {
        return 'Tag ' . e($slug);
    }

    public function archive(string $month, string $year): string
    {
        return "Archive {$year}-{$month}";
    }

    public function store(): string
    {
        return 'Created';
    }

    public function destroy(int $id): string
    {
        return "Deleted {$id}";
    }

    public function about(): string
    {
        return 'About';
    }

    public function feed(string $format): string
    {
        return "Feed {$format}";
    }
}

With these routes, GET /posts/7 runs show(7), GET /posts/abc answers 404 (the \d+ constraint does not match), GET /tags/php runs tag('php') and GET /archive/2026/11 runs archive('11', '2026').

php taphra route:list prints the routes the router serves.

In code, Router::getInstance()->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 <img> 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.

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).

Adding routes from PHP

#

addRoute() and addRouteGroup() register routes at run time, for example in app/bootstrap.php:

app/bootstrap.php
<?php
// app/bootstrap.php
$GLOBALS['APP_MODE'] = modeFromEnvironment(getenv('APP_ENV'));

$router = \Taphra\Router::getInstance();

// addRoute(method, pattern, target, name, middleware)
$router->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
<?php
// src/BlogServiceProvider.php in the acme/blog package
namespace Acme\Blog;

use Taphra\Router;
use Taphra\ServiceProvider;

class BlogServiceProvider extends ServiceProvider
{
    public function register(): void {}

    public function boot(): void
    {
        Router::getInstance()->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
<?php
// src/Controllers/PostController.php in the acme/blog package
namespace Acme\Blog\Controllers;

class PostController extends \Taphra\Controller
{
    public function index(): string
    {
        return 'All posts';
    }

    public function show(int $id): string
    {
        return "Post {$id}";
    }

    public function store(): string
    {
        return 'Created';
    }
}

The app lists the provider in app/Config/app.yml (see Service providers):

YAML
all:
  providers:
    - Acme\Blog\BlogServiceProvider
  • Targets work like the app's, with the controller looked up in the package's namespace: post/show is PostController::show() there. A target can also give the full class name of a controller in that namespace or below it (Acme\Blog\Controllers\Admin\PageController/edit). A package route can only target the package's own controllers: a target outside the namespace (one of your controllers, another package's, a global class) is refused when the routes are added, with an InvalidArgumentException that names the route, and nothing of that call is added. The app's own controller namespace (App\Controllers) cannot be passed as a package's. The routes take the same forms as a route group's ('GET /path' => 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.

app/Middleware/RequireToken.php
<?php
// app/Middleware/RequireToken.php
namespace App\Middleware;

use Nyholm\Psr7\Response;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Server\RequestHandlerInterface;

class RequireToken implements MiddlewareInterface
{
    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
    {
        if (!hash_equals('change-me', $request->getHeaderLine('X-Token'))) {
            return new Response(401, ['Content-Type' => 'text/plain'], 'Missing or wrong token');
        }
        return $handler->handle($request);
    }
}
app/Controllers/AdminController.php
<?php
// app/Controllers/AdminController.php
namespace App\Controllers;

class AdminController extends AppController
{
    public function stats(): string
    {
        return 'Stats';
    }
}

php taphra make:middleware Name writes a stub to app/Middleware/Name.php in the App\Middleware namespace, which the skeleton's PSR-4 autoloading finds by its file name.

On the default entry (index.php creating a FrontController), route middleware acts as a gate: it can let the request through or answer instead of the action, but it cannot change the action's response. Use the PSR-15 pipeline for middleware that rewrites responses.

A middleware pipeline for every request

#

The skeleton's index.php dispatches with new FrontController(). To run middleware on every request (CORS, JSON body parsing, rate limiting, request IDs), build a pipeline in index.php instead and end it with ActionDispatcherMiddleware:

PHP
<?php
// app/Static/index.php
require_once __DIR__ . '/indexcommon.php';

use Taphra\Http\ActionDispatcherMiddleware;
use Taphra\Http\MiddlewarePipeline;
use Taphra\Http\RequestBodyMiddleware;
use Taphra\Http\SecurityHeadersMiddleware;
use Taphra\Http\ServerRequestFactory;

$response = (new MiddlewarePipeline())
    ->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 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).

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/<controller>/<action>.tpl.php in the layout; public properties you set on the controller are the view's variables (Views and helpers).
  • RestController::json($data, $status = 200) returns a JSON body and sets the status and Content-Type.
app/Controllers/AccountController.php
<?php
// app/Controllers/AccountController.php
namespace App\Controllers;

use Taphra\Exceptions\HttpException;
use Taphra\Exceptions\NotFoundException;

class AccountController extends AppController
{
    public function beforeAction()
    {
        parent::beforeAction();   // keeps the CSRF check
        $this->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). 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).

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 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 '';.