Search by

seba1rx / exhaust

seba1rx

Exhaust — minimalist SPA-oriented PHP framework

Package info

github.com/seba1rx/Exhaust

pkg:composer/seba1rx/exhaust

Statistics

Installs: 25

Dependents: 0

Suggesters: 0

Stars: 0

Open Issues: 0

v1.2.1 2026-11-30 23:07 UTC

This package is auto-updated.

Last update: 2026-11-30 23:07:57 UTC


README

Minimalist PHP framework built around a commands-based response pattern for single-page applications. The primary mode of interaction is a set of typed commands that the frontend engine (engeen.js) interprets and executes. The framework also supports pure API responses for clients that consume JSON directly, without engeen.js.

Core Philosophy

SPA mode — the primary use case:

Browser  ──XHR/Fetch──▶  PHP Controller  ──Commands JSON──▶  engeen.js

When the user interacts with the SPA, the frontend sends an asynchronous request (XHR or Fetch) to a PHP controller. The controller builds a response by calling static methods on Commands, which queue up instructions. At the end of the request cycle the framework serialises those instructions as JSON and engeen.js executes them in order (FIFO).

API mode — when the backend is consumed as a plain REST API:

Client  ──HTTP──▶  PHP Controller  ──Plain JSON──▶  Client

The Commands::apiResponse() method sends a plain JSON object not intended for engeen.js. Use this when the controller serves a mobile app, a third-party client, or any consumer that reads JSON directly without the SPA engine.

Installation

composer require seba1rx/exhaust

The package does not publish any files automatically — copy the base configuration from vendor/seba1rx/exhaust/stubs/config/ into your app's config/ directory and adjust it to your needs:

cp -r vendor/seba1rx/exhaust/stubs/config/. config/

Project structure

your-app/
├── public/index.php            ← single entry point
├── public/assets/js/
│   ├── engeen.js               ← frontend engine
│   └── drivers/                ← dialog/toast drivers (SweetAlert2, Notiflix, …)
├── App/
│   ├── Controllers/
│   │   └── Controller.php      ← app-level base controller (handles middlewares)
│   ├── Middlewares/
│   └── Models/
├── config/
│   ├── config.php              ← global configuration
│   └── routes.php              ← route definitions
└── resources/templates/        ← views

The package (seba1rx/exhaust) provides the Exhaust\ namespace. Your application code lives in the App\ namespace. Controllers, middlewares and models are app concerns — the package does not define a controller base class.

Routing

Routes are defined in config/routes.php using the Route object.

use App\Controllers\Wellcome;
use App\Controllers\UserController;

$routes = new Route();

$routes->registerGetRoute('/', [Wellcome::class, 'showLandingPage'])->name('home');

$routes->registerPostRoute('/users', [UserController::class, 'store'])
       ->name('users.store')
       ->middlewares(['Authentication']);

$routes->registerGetRoute('/users/{id}', [UserController::class, 'show'])
       ->name('users.show');

$routes->registerPutRoute('/users/{id}', [UserController::class, 'update']);
$routes->registerDeleteRoute('/users/{id}', [UserController::class, 'destroy']);

// Single-action controller — no method, class must be invokable
$routes->registerDeleteRoute('/session', [\App\Controllers\Logout::class]);
Method Helper
GET registerGetRoute($path, $action)
POST registerPostRoute($path, $action)
PUT registerPutRoute($path, $action)
PATCH patch($path, $action)
DELETE registerDeleteRoute($path, $action)

Short aliases get(), post(), put(), patch() and delete() do the same.

Route parameters wrapped in {braces} are passed to the action in declaration order, followed by the payload array: show(int $id, array $payload). They also stay available as app()->request->routeParam('id'). Every literal segment must match, and an unknown method on a known path answers 405.

Matching order

Router::match() is deterministic: among the routes with the same method and segment count, the one with more literal segments wins, whatever the declaration order. So /users/me and /users/{id} can live together, and /users/me always answers /users/me. A tie is only possible between ambiguous routes (below); the route declared first wins. HEAD falls back to GET, and params are URL-decoded.

Ambiguous routes, route:check and route:cache

Two routes are ambiguous when they have the same method, the same number of segments, the same number of literals, and every position is compatible (equal literals, or a param on either side): /a/{x} and /{y}/b, /{a} and /{b}, or the same path twice. new Router($routes) throws Exhaust\Routing\AmbiguousRoutesException (an \Exception) naming method, paths and actions; pairs() returns all of them.

The check costs a few milliseconds per request with hundreds of routes, so App only runs it in debug (debug.backend), or when routing.check_ambiguity is true. In production, check in CI and cache on deploy:

php bin/engeen route:check    # table of ambiguous pairs, exit code 1 when there is any
php bin/engeen route:cache    # writes storage/cache/routes.php (fails, without a file, on ambiguity or closures)
php bin/engeen route:clear
php bin/engeen route:list     # works with ambiguous routes too; shows the session mode

App reads storage/cache/routes.php while config/routes.php and every file it includes keep their modification time and size; editing any of them silently falls back to routes.php. With a fresh cache routes.php does not run, so anything else it does (Pipeline::alias(...), constants, helpers) is lost: register aliases and other side effects in bootstrap.php (route:cache warns when routes.php registers aliases). Only plain data can be cached: middlewares must be string specs ('throttle:60,60', HmacSignature::class . ':secret'), not closures or instances (route:cache names the route, key and index). With opcache.validate_timestamps=0, restart PHP-FPM/Apache (or reset opcache) after route:cache.

Read-only session routes

PHP's file session handler locks the session until the request ends, so parallel requests of one user (several panels loading at once) run one after another. A read-only route releases the lock right before its controller:

$routes->get('/dashboard/stats', [Stats::class, 'show'])->readOnlySession();

$routes->group(['session' => 'readonly'], function (Route $r) {
    $r->get('/reports/{id}', [Reports::class, 'show']);
    $r->post('/reports/{id}/star', [Reports::class, 'star'])->readOnlySession(false);   // this one writes
});

Routes without a mode follow session.default_mode ('write' by default); /health and /ready are read-only. Things to know before marking a route read-only:

  • The lock is released after routing, before the route middlewares and the controller.
  • $_SESSION stays readable, but what the middlewares and the controller write is discarded. Write through app()->sessionManager->write(fn () => $_SESSION['cart'] = $cart), which reopens the session, runs the callback and releases it again. Middlewares that write the session (rotating CSRF tokens, switching company) need write(), or the route must not be read-only. In debug, a discarded write is logged as a warning.
  • Reopening needs no output yet: after echo it throws SessionReopenException (buffer with ob_start()).
  • Each request sends exactly one session cookie, with HttpOnly (and Secure under HTTPS). This needs seba1rx/sessionadmin 3.0.2 or later.
  • createUserSession() replaces the id before authenticating. If it can not (output already sent) it throws SessionAdminException (SessionReopenException on a released session) and the user is not logged in; a session that was already authenticated stays so. Catch both, call terminate() and answer with a dialog. Do not fire parallel requests while it runs: one that still carries the old id can overwrite the new cookie.
  • createUserSession() (login) and terminate() (logout) reopen the session by themselves, and the new session id reaches the browser in the response cookie. Keep session.use_strict_mode=1 (the production recommendation): it makes PHP reject session ids it did not create. When upgrading from seba1rx/sessionadmin 3.0.1 or earlier, empty the session store on deploy (everyone logs in again): sessions already authenticated are not invalidated by the upgrade.
  • Parallel requests see a snapshot: a read-only request does not see what a concurrent write request saves after it started.

The session manager must implement Exhaust\Contracts\ReleasableSessionBlueprint (ExhaustSessionAdmin does).

Controllers

Controllers live in App\Controllers\ and extend your app-level Controller base class (which handles middleware execution). Each action receives the request payload as an associative array and must return Commands::all().

namespace App\Controllers;

use App\Controllers\Controller;
use Exhaust\Response\Commands;

class UserController extends Controller
{
    public function edit(array $payload): array
    {
        $html = app()->render('user/edit.html.twig', ['id' => $payload['id']]);

        Commands::html('content-section', $html);

        return Commands::all();
    }

    public function destroy(array $payload): array
    {
        // … delete logic …

        Commands::dialog(type: 'success', options: Commands::dialogBuilder(
            icon: 'success',
            title: 'Deleted',
            btn_confirm: ['text' => 'Ok', 'callback' => "Engeen.route('/users')"],
        ));

        return Commands::all();
    }
}

The app-level Controller base constructor handles middlewares:

namespace App\Controllers;

class Controller
{
    public function __construct(array $middlewares)
    {
        $this->invokeBeforeMiddlewares($middlewares, app()->request->payload);
    }
    // …
}

Commands reference

All methods are static on Exhaust\Response\Commands. Commands accumulate in a static array and are flushed at the end of each request by app()->run().

html — inject HTML into a DOM element

Commands::html('content-section', '<p>New content</p>');
Commands::html('sidebar', app()->render('partials/sidebar.twig', $data));

Multiple calls are applied in order. The frontend does document.getElementById(id).innerHTML = content.

script — run arbitrary JavaScript

The snippet is minified automatically before sending. Successive calls accumulate in call order (joined with ;\n), so a helper adding a script does not overwrite the controller's. Blank snippets are ignored; replace: true drops what was added before.

Commands::script("myApp.loadSection('profile')");
Commands::script("myApp.highlightMenu('users')");    // script = "myApp.loadSection('profile');\nmyApp.highlightMenu('users')"
Commands::script('onlyThis()', replace: true);

The command stays a single string, so older copies of engeen.js keep running it.

reset / toResponse

Commands::reset();                           // drop every command (tests, long-running workers)
return Commands::toResponse(422);            // validate the commands and send them as JSON with a status

assignValue — set a JavaScript variable

Commands::assignValue('currentUserId', 42);
Commands::assignValue('config', ['theme' => 'dark', 'lang' => 'es']);

dialog + dialogBuilder — SweetAlert2 modal

// Recommended: use dialogBuilder for readable named parameters
Commands::dialog(type: 'success', options: Commands::dialogBuilder(
    icon: 'success',
    title: 'Saved',
    text: 'Your changes have been saved.',
    btn_confirm: ['text' => 'Ok', 'callback' => 'Engeen.route("/dashboard")'],
));

Commands::dialog(type: 'warning', options: Commands::dialogBuilder(
    icon: 'warning',
    title: 'Are you sure?',
    btn_confirm: ['text' => 'Yes, delete', 'class' => 'btn-danger', 'callback' => 'deleteItem()'],
    btn_cancel:  ['text' => 'Cancel'],
));

Commands::dialog(type: 'info', options: Commands::dialogBuilder(
    icon: 'info',
    title: 'Session expiring',
    timer: ['time' => 5000, 'callback' => 'logout()'],
    showLoading: true,
));

dialogBuilder parameters

Parameter Type Description
icon string success error info warning question
title string|null Large heading text
text string|null Body message
html string|null HTML body — overrides text, minified automatically
btn_confirm array|null {text, ?class, ?callback}
btn_deny array|null {text, ?class, ?callback}
btn_cancel array|null {text, ?class, ?callback}
timer array|null {?time: int (ms, multiple of 1000), ?callback}
showLoading string|true|null Show a loading indicator inside the dialog

toast — SweetAlert2 toast notification

Commands::toast('success', [
    'title'    => 'Changes saved',
    'duration' => 3000,
    'position' => 'top-end',
]);

Commands::toast('error', ['title' => 'Something went wrong', 'duration' => 5000]);

Allowed types: success error info warning question any

Allowed positions: top top-start top-end center center-start center-end bottom bottom-start bottom-end

log — typed browser console output

Sends a colour-coded log entry to the browser console. Overrides the framework's debug_request config for this response.

Commands::log(type: 'info',    text: 'User created',   details: ['id' => 5]);
Commands::log(type: 'warning', text: 'Slow query',      details: ['ms' => 820]);
Commands::log(type: 'error',   text: 'Payment failed');
Commands::log(type: 'debug',   details: $payload);

Allowed types: info error debug warning

console_log — raw console.log

Commands::console_log('checkpoint reached');
Commands::console_log(['key' => 'value', 'count' => 3]);

echo — send a full HTML page

Used for navigation requests. The content bypasses the commands engine and is rendered directly as HTML.

Commands::echo(html: app()->render('landing/landing.html.twig'));

apiResponse — plain JSON response (API mode)

Sends a plain JSON object. The response is not processed by engeen.js — it is intended for clients that consume the backend as a REST API (mobile apps, third-party integrations, etc.). Cannot be combined with other commands in the same response.

Commands::apiResponse(['users' => $list, 'total' => count($list)]);

includeScript / includeCss — inject assets dynamically

engeen.js loads these files before running the other commands of the same response, so html and script can use them right away:

  • scripts load one after the other, in the order given;
  • each file is loaded once per page (also when it is already in the page);
  • a file that fails is logged and the rest keeps running.

Duplicates are detected by the full URL. Both methods accept one URL or a list.

Commands::includeCss('/assets/css/chart.css');
Commands::includeScript(['/assets/js/chart.min.js', '/assets/js/chart-plugins.js']);
Commands::script('renderChart(' . json_encode($data) . ')');

The JSON keys are includeScript and includeCss, each holding a list of URLs. Copy the 1.2 engeen.js to public/: older copies ignore these commands.

A complete controller action

public function saveProfile(array $payload): array
{
    $bio = $payload['bio'] ?? '';

    if (empty($bio)) {
        Commands::dialog(type: 'warning', options: Commands::dialogBuilder(
            icon: 'warning',
            title: 'Validation error',
            text: 'Bio cannot be empty.',
        ));
        return Commands::all();
    }

    // persist …
    app()->dbLink->update(
        'UPDATE users SET bio = :bio WHERE id = :id',
        [':bio' => $bio, ':id' => $payload['userId']]
    );

    Commands::html('profile-bio', htmlspecialchars($bio));
    Commands::toast('success', ['title' => 'Profile updated', 'duration' => 3000, 'position' => 'top-end']);
    Commands::log(type: 'info', text: 'Profile saved', details: ['userId' => $payload['userId']]);

    return Commands::all();
}

The JSON sent to the frontend:

{
  "html":  { "profile-bio": "New bio text here" },
  "toast": { "success": { "title": "Profile updated", "duration": 3000, "position": "top-end" } },
  "log":   { "info": { "text": "Profile saved", "details": { "userId": 7 } } }
}

Frontend — engeen.js

The frontend counterpart of the framework. Exposes a global Engeen object with no external dependencies (dialogs and toasts are delegated to a registered driver).

Setup

<!-- 1. dialog library -->
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>

<!-- 2. engeen core -->
<script src="/assets/js/engeen.js"></script>

<!-- 3. driver -->
<script src="/assets/js/drivers/engeen-swal2-driver.js"></script>

<!-- 4. register driver -->
<script>Engeen.setDialogDriver(EngeenSwal2Driver);</script>

Sending requests

Engeen.request.post({ url: '/users', payload: { name: 'Alice' }, showLoading: true });
Engeen.request.get({ url: '/users', payload: { page: 2 } });
Engeen.request.put({ url: '/users/7', payload: { bio: 'Hello' } });
Engeen.request.delete({ url: '/users/7', payload: { id: 7 } });

Request options

Option Description
url Target route (required)
payload Data to send as request body
showLoading Show a loading dialog — true or a string title
before_script JS evaluated before sending
done_script JS evaluated after the response is processed

fetch() requests must include X-Requested-With: fetch so the backend detects RequestType::Fetch. engeen.js adds this header automatically.

How commands are processed

Engeen.executeCommands(response) iterates the JSON received from the server:

JSON key Browser effect
html document.getElementById(id).innerHTML = content
script eval(script)
console_log console.log(value)
log.info/error/debug/warning Colour-coded console output
dialog Delegated to the registered driver
toast Delegated to the registered driver
assignValue Assigns a global JS variable via eval()

Errors and Engeen.request.onError

Error answers of the framework (404, 405, 422, 500…) carry commands (log + dialog), so engeen.js runs them whatever the status and the screen never freezes. When an answer has no commands — a network error (status 0), an HTML/text error page, or a 4xx/5xx JSON without commands — Engeen.request.onError(status, data) runs. The default opens an error dialog with the driver (title Error {status}, Unexpected response for a 2xx that is not JSON, or Network error; data.error as text), or logs to the console and closes the loading dialog without a driver. Override it:

Engeen.request.onError = (status, data) => {
    if (status === 401) return Engeen.route('/login');
    Engeen.popDialog.error({ title: `Error ${status}`, text: data?.error ?? 'Try again' });
};

done_script always runs. Copy the new engeen.js to public/ when upgrading.

Triggering dialogs and toasts directly from JS

Engeen.popDialog.success({ title: 'Saved', text: 'All good.', buttons: { confirm: { text: 'Ok' } } });
Engeen.popDialog.error({ text: 'Something went wrong' });
Engeen.popDialog.any({ loading: true, title: 'Processing…' });

Engeen.popToast.success({ title: 'Done', duration: 3000, position: 'top-end' });
Engeen.popToast.warning({ title: 'Watch out' });

Utilities

Engeen.route('/dashboard');         // navigate — window.location.replace
Engeen.redirect('https://…');      // alias

Engeen.console.info('msg', obj);
Engeen.console.error('msg', obj);
Engeen.console.debug('msg', obj);
Engeen.console.warning('msg', obj);

Engeen.form.getData('form-id');     // FormData → plain object

Engeen.tab.id;                      // unique UUID for this browser tab

Request object

Available via app()->request inside any controller.

app()->request->payload               // stdClass — all body params, type-cast automatically
app()->request->uri->path             // '/users/7'
app()->request->getRequestMethod()    // 'POST'
app()->request->isAsync()             // true for XHR and Fetch
app()->request->isNavigation()        // true for regular browser navigation
app()->request->getRemoteAddress()
app()->request->getUriParam('page')   // query string: ?page=2
app()->request->hasUpload()

Payload values are automatically cast to their detected type: "42" → 42, "1.5" → 1.5, "TRUE"/"FALSE" → booleans, "007" and huge numbers stay strings, nested arrays are walked. JSON null stays null and booleans stay booleans.

Apps that relied on the 1.0 behaviour (null → "") can turn on "request" => ["legacy_null_as_empty_string" => true] while they migrate. It applies at any depth, logs a deprecation once per request in debug, and will be removed in 2.0:

// 1.0: {"note": null} → ''   ·   1.1+: null
$note = (string) ($payload['note'] ?? '');

Paths in request.ignore are compared by whole leading segments: 'assets', '/assets' and 'assets/' ignore /assets and /assets/x.js but not /assetsx; 'assets/vendor' only ignores that directory. Ignored paths that still reach PHP answer 404.

PSR interoperability

The package ships three contracts in Exhaust\Contracts\ that align the framework with PSR standards without changing the existing workflow.

RequestBlueprint — typed request contract

Request now implements RequestBlueprint (which extends UrlBlueprint). Type-hint against the contract wherever you want static-analysis tools and IDEs to understand the full API of the request object.

use Exhaust\Contracts\RequestBlueprint;

// Type-hinting in a service or utility that receives the request
public function audit(RequestBlueprint $request): void
{
    $method  = $request->getRequestMethod(); // 'POST'
    $ip      = $request->getRemoteAddress(); // '192.168.1.10'
    $payload = $request->payloadAsArray();   // ['userId' => 7, 'action' => 'delete']
    $isXHR   = $request->isAsync();          // true
}

Request::toPsr7() — PSR-7 adapter

Converts the framework request into a Psr\Http\Message\ServerRequestInterface on demand, for use with PSR-15 middleware or any library that expects a PSR-7 object.

Requires a PSR-17 ServerRequestFactoryInterface implementation — install any compliant library in your app:

composer require nyholm/psr7
use Nyholm\Psr7\Factory\Psr17Factory;

$factory    = new Psr17Factory();
$psr7       = app()->request->toPsr7($factory);

// Pass to any PSR-15 middleware or PSR-7-aware library
$psr7       = $psr7->withAttribute('user', $currentUser);
$response   = $someExternalMiddleware->process($psr7, $handler);

The adapter maps:

Framework request PSR-7 ServerRequest
$request->method getMethod()
$request->uri->string getUri()
$_SERVER['HTTP_*'] getHeaders()
$request->payloadAsArray() getParsedBody()
$request->uri->query (parsed) getQueryParams()
$_COOKIE getCookieParams()
$_SERVER getServerParams()

MiddlewareBlueprint — PSR-15 middlewares

MiddlewareBlueprint extends PSR-15 MiddlewareInterface. Implementing it gives:

  • interoperability with third-party PSR-15 libraries (CORS, rate-limiting, JWT auth, etc.)
  • explicit, type-safe contract over the legacy invokable pattern
  • IDE completion and static-analysis support

PSR-15 middleware (recommended for new middlewares):

namespace App\Middlewares;

use Exhaust\Contracts\MiddlewareBlueprint;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\RequestHandlerInterface;
use Nyholm\Psr7\Response;

final class AuthMiddleware implements MiddlewareBlueprint
{
    /**
     * Validates the session and either short-circuits with a redirect or
     * delegates to the next handler in the pipeline.
     *
     * @param ServerRequestInterface  $request
     * @param RequestHandlerInterface $handler
     * @return ResponseInterface
     */
    public function process(
        ServerRequestInterface  $request,
        RequestHandlerInterface $handler,
    ): ResponseInterface
    {
        if (!isset($_SESSION['user'])) {
            // Short-circuit: return a redirect without reaching the controller
            return (new Response(302))->withHeader('Location', '/login');
        }

        // Delegate to the next middleware or the controller
        return $handler->handle($request);
    }
}

Legacy invokable middleware (still fully supported):

namespace App\Middlewares;

final class AuthMiddleware
{
    /** Redirects to login if no active session exists. */
    public function __invoke(): void
    {
        if (!isset($_SESSION['user'])) {
            header('Location: /login');
            exit;
        }
    }
}

Updating App\Controllers\Controller to support both patterns:

The app-level Controller base detects whether each middleware implements MiddlewareBlueprint and dispatches accordingly. Middlewares that don't implement the interface continue to work as invokables.

namespace App\Controllers;

use Exhaust\Contracts\MiddlewareBlueprint;
use Nyholm\Psr7\Factory\Psr17Factory;

class Controller
{
    public function __construct(array $middlewares)
    {
        $this->invokeBeforeMiddlewares($middlewares, app()->request->payload);
    }

    /**
     * Executes each middleware before the controller action.
     * Supports both PSR-15 (MiddlewareBlueprint) and legacy invokable middlewares.
     *
     * @param array     $middlewares List of middleware class names.
     * @param \stdClass $payload     Current request payload.
     * @return void
     */
    public function invokeBeforeMiddlewares(
        array $middlewares,
        \stdClass $payload = new \stdClass,
    ): void
    {
        $factory = new Psr17Factory();

        foreach ($middlewares as $className) {
            $middleware = new ("\\App\\Middlewares\\{$className}")();

            if ($middleware instanceof MiddlewareBlueprint) {
                // PSR-15 path
                $psr7    = app()->request->toPsr7($factory);
                $handler = new \App\Http\FinalHandler($factory);
                $middleware->process($psr7, $handler);
            } else {
                // Legacy invokable path
                $middleware($payload);
            }
        }

        if (app()->terminate_session) {
            app()->response = new \stdClass;
        }
    }
}

FinalHandler is a minimal pass-through that closes the middleware pipeline. Exhaust controllers handle the actual HTTP response through Commands, not through PSR-7 response objects.

namespace App\Http;

use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\RequestHandlerInterface;
use Nyholm\Psr7\Factory\Psr17Factory;

/**
 * Terminal handler for the PSR-15 middleware pipeline.
 *
 * Returns an empty 200 response — the actual response body is built by
 * Exhaust's Commands system and sent separately by app()->run().
 */
final class FinalHandler implements RequestHandlerInterface
{
    public function __construct(private readonly Psr17Factory $factory) {}

    /**
     * @param ServerRequestInterface $request
     * @return ResponseInterface
     */
    public function handle(ServerRequestInterface $request): ResponseInterface
    {
        return $this->factory->createResponse(200);
    }
}

ResponseBlueprint — response contract

ResponseBlueprint defines the contract for objects that wrap the Commands array and send an HTTP response. Implement it to build a custom response class — useful when you need extra headers, content negotiation, structured error envelopes, or centralised response logging.

namespace App\Http;

use Exhaust\Contracts\ResponseBlueprint;
use Exhaust\Exceptions\LogicException;
use Exhaust\Request\RequestType;
use Exhaust\Tools\CastingTool;

/**
 * Wraps the validated Commands array and serialises it as HTML or JSON
 * depending on the originating request type.
 */
final class Response implements ResponseBlueprint
{
    /**
     * @param array       $commands    Validated command set from Commands::all().
     * @param RequestType $requestType Detected type of the originating request.
     */
    public function __construct(
        private readonly array       $commands,
        private readonly RequestType $requestType,
    ) {}

    /** {@inheritdoc} */
    public function getCommands(): array
    {
        return $this->commands;
    }

    /** {@inheritdoc} */
    public function toJson(): string
    {
        return json_encode(CastingTool::arrayToObject($this->commands));
    }

    /**
     * {@inheritdoc}
     * @throws LogicException When the Commands set has no 'echo' entry.
     */
    public function toHtml(): string
    {
        if (!isset($this->commands['echo'])) {
            throw new LogicException('Response has no echo command — cannot render HTML.');
        }
        return $this->commands['echo'];
    }

    /** {@inheritdoc} */
    public function send(): void
    {
        if ($this->requestType === RequestType::Navigation) {
            header('Content-Type: text/html; charset=UTF-8');
            echo $this->toHtml();
        } else {
            header('Content-Type: application/json; charset=utf-8');
            echo $this->toJson();
        }
    }
}

Usage at the end of a controller action or inside app()->run():

use Exhaust\Response\Commands;
use App\Http\Response;

// Build commands as usual …
Commands::html('content', $html);
Commands::toast('success', ['title' => 'Saved', 'duration' => 3000]);

// Wrap in the concrete Response and send
$response = new Response(
    commands:    Commands::all(),
    requestType: app()->request->requestType,
);
$response->send();

Server-to-server APIs (webhooks, integrations)

The SPA flow above needs X-Requested-With. Webhooks, payment callbacks and other servers never send it, so routes can be declared as api or raw: they always reach the controller, whatever the headers.

use Exhaust\Http\Middleware\HmacSignature;
use Exhaust\Http\Middleware\Idempotent;

$routes->group(['prefix' => 'webhooks', 'type' => 'api', 'middleware' => ['throttle:120,60']], function (Route $r) {
    $r->post('/uber', [UberWebhook::class, 'receive'])
      ->middleware([
          new HmacSignature(secret: fn (Request $req) => Store::secretFor($req->json()['store_id'] ?? null), header: 'X-Uber-Signature'),
          new Idempotent(fn (Request $req) => $req->json()['event_id'] ?? null),
      ])
      ->name('webhooks.uber');
});

$routes->get('/status', [StatusController::class])->api();   // single route
Type Dispatch Errors
spa (default) navigation renders the main template, XHR/fetch reach the controller Commands (dialog) for XHR/fetch, HTML curtain for browsers
api always the controller JSON {error, code, request_id} with the right status
raw always the controller text/plain (JSON when the client asks for it)

Every error has the right status in every format; see HTTP errors and status codes.

Set "headless" => true in config/config.php for an API-only app: no template engine is loaded and every route behaves like api.

Responses

Controllers return a Response (no more echo + exit). Arrays are sent as JSON, strings as text, null as 204.

use Exhaust\Response\Response;

return Response::json(['status' => 'queued'], 202);
return Response::noContent();
return Response::text('pong')->header('Cache-Control', 'no-store');
throw new HttpException(422, 'Invalid order', details: ['field' => 'items']);

Unexpected exceptions on api routes answer a generic 500. The message is shown only when debug.backend is on.

Request: raw body and headers

$request = app()->request;
$request->rawBody();                 // exact bytes received (for HMAC checks)
$request->json();                    // decoded body, HttpException 400 when invalid
$request->header('X-Signature');     // case-insensitive
$request->bearerToken();
$request->id();                      // X-Request-Id or a generated one
$request->routeParam('id');
Request::create('POST', '/webhooks/uber', ['X-Signature' => $sig], $body);   // tests, CLI

Route middlewares

Run by the router around the controller, they can short-circuit by returning a Response or throwing an HttpException. Implement Exhaust\Contracts\RouteMiddlewareBlueprint (handle(Request $request, \Closure $next): mixed), or use a closure.

Middleware Alias Purpose
ApiToken token Bearer / header token, static list or resolver
HmacSignature hmac HMAC of the raw body, per-request secret, optional timestamp window
RateLimit throttle:60,60 fixed window per IP or custom key, 429 + Retry-After
IpAllowlist ip:10.0.0.0/8,1.2.3.4 IPv4/IPv6 and CIDR
Idempotent idempotent:Idempotency-Key answers 200 to repeated events without running the controller
Tenancy\ResolveTenant sets the current tenant

Legacy ->middlewares([...]) (short names run by the app's base Controller) keep working unchanged.

Health

GET /health (liveness) and GET /ready (registered checks, 503 when one fails) are added unless the app defines those paths. Register checks with Health::check('queue', fn () => Queue::driver()->size('webhooks') < 10000 ?: 'backlog'). Configure under "health" in the config.

HTTP errors and status codes

App::run() answers every outcome with a Response that has an explicit status (a status set earlier with http_response_code() never leaks, and HEAD gets no body). Errors go through Exhaust\Exceptions\ErrorResponder, which picks the format with Exhaust\Http\ContentNegotiator:

  1. raw route and the client does not want JSON → Text (404 Not Found)
  2. api route, raw route wanting JSON, or headless app → Json ({error, code, request_id})
  3. async request (X-Requested-With: xmlhttprequest or fetch) → Commands (log + dialog, plus error, code, request_id)
  4. the client wants JSON (Accept/Content-Type) → Json
  5. Accept mentions text/html (browsers) → Html (curtain)
  6. anything else (curl, */*, image/*) → Text

Throw the exception that says what happened; its message is shown to the client:

Exception Status Extras
BadRequestHttpException($message, $details) 400
UnauthorizedHttpException($challenge, $message) 401 WWW-Authenticate when $challenge is given
ForbiddenHttpException 403
NotFoundHttpException 404
MethodNotAllowedHttpException($allowed) 405 Allow
ConflictHttpException 409
UnprocessableEntityHttpException($errors) 422 errors field in the JSON body
TooManyRequestsHttpException($retryAfter) 429 Retry-After
ServiceUnavailableHttpException($retryAfter) 503 Retry-After
HttpException($status, ...) any all of them extend it

Other exceptions are a 500 with a generic message. The real message is shown with debug.backend, and also to SPA users (dialog, curtain) with exception.show_detail; api clients never see it because of show_detail.

Situation Status Json Text Commands Html
Route OK 200 / the controller's Response / 204 for null (api) body body commands template
Browser GET/HEAD to an unknown path 200 (SPA deep-link fallback) – – – main template
Unknown path (anything else) 404 {error, code} 404 Not Found app NotFound commands or 404 dialog curtain 404
Known path, other method 405 + Allow yes yes dialog curtain
Path in request.ignore that reached PHP 404 yes yes yes curtain
Remote address not allowed 403 (Forbidden; the address goes to the log, and to remote_address with debug) yes yes dialog curtain
Middleware 401/403/429 same, with WWW-Authenticate/Retry-After yes yes dialog curtain
HttpException from a controller its status message message dialog curtain
Unexpected Throwable / invalid commands 500 generic (message with debug) same generic (show_detail or debug) 500 curtain
Maintenance / construction 503 + Retry-After yes yes dialog the maintenance template
HEAD same as GET no body
Error before run() without app 500 minimal minimal <h1>
Expired session (terminate_session) 200 (unchanged) {} (unchanged)

Unknown paths from engeen.js. An async request to an unknown path runs the invokable routing.not_found_controller (default App\Controllers\NotFound, null disables it). Its commands are sent with status 404; return a Response to choose another status, e.g. return Response::json(Commands::all(), 200);.

Curtains. resources/html_curtains/{status}.html, then 4xx.html/5xx.html, then 500.html, which answers any status as in 1.1 (the old html_courtains/ directory still works). Add 404.html or 4xx.html so client errors do not show the server error page; a single curtain can also branch on $status. They are PHP files with the 1.1 variables in scope: $t (the Throwable, or an HttpException for a bare status), $conf, $request and $debug, plus $status, $message (client-safe) and $requestId. Without curtains the page is <h1>404 Not Found</h1>. A curtain must tolerate $conf === null (it happens when the error occurs before the app finished booting).

Encoding. Commands and error bodies replace invalid UTF-8 with U+FFFD (an exception message from a latin1 database still shows); Response::json() of your own controllers still fails on it.

Dialog texts come from exception.dialog.title / text (placeholders {status}, {reason}, {message}). By default the title is the reason phrase and the text is the message, or "Contact the system manager or try again" for a hidden server error.

Reporting and custom renderers. Exceptions answered with status ≥ 500 are written to error_log with request id, method, path, class, message and location (plus the trace with exception.show_trace). That includes HttpExceptions ≥ 500 thrown on purpose; bare statuses (forStatus(): maintenance 503, 404, 405) are never reported. Errors handled by run() no longer reach the app's set_exception_handler, so plug your tracker in here:

use Exhaust\Exceptions\ErrorResponder;
use Exhaust\Http\ResponseFormat;

ErrorResponder::reportUsing(fn (\Throwable $e, Request $request) => \Sentry\captureException($e));
ErrorResponder::reportUsing(fn ($e, $r) => $e instanceof ServiceUnavailableHttpException ? null : Sentry::capture($e));   // skip planned 503s
ErrorResponder::use(ResponseFormat::Html, new MyErrorPages());     // implements ErrorRendererBlueprint
ErrorResponder::respond($e, $request);                             // build the same answer yourself
ErrorResponder::reset();                                           // tests

App::enMantencion(?int $retryAfter) and enConstruccion() answer 503 with Retry-After (default maintenance.retry_after): browsers get the curtain template, other clients the 503 in their format. maintenanceResponse() / constructionResponse() build it without sending.

jQuery clients. With real statuses, $.ajax runs .fail() instead of .done() for 4xx/5xx. Use .always(), or .fail(xhr => run(xhr.responseJSON)), or keep 200 by returning Response::json(Commands::all(), 200) from the NotFound controller. engeen.js is not affected.

Queues and workers

final class ProcessUberOrder extends \Exhaust\Queue\Job
{
    public int $tries = 5;              // then moved to failed_jobs
    public int $timeout = 60;
    public ?string $queue = 'webhooks';

    public function __construct(public readonly string $eventId, public readonly string $raw) {}

    public function uniqueKey(): ?string { return 'uber:' . $this->eventId; }   // dedup while pending
    public function backoff(int $attempt): int { return 30 * $attempt; }         // default: 10s, 20s, 40s…
    public function handle(): void { /* … */ }
}

Queue::push(new ProcessUberOrder($id, $request->rawBody()));
  • Drivers: DatabaseQueue (default; MySQL 8+/MariaDB 10.6+, FOR UPDATE SKIP LOCKED) and MemoryQueue. Plug Redis/SQS by implementing QueueBlueprint and calling Queue::use().
  • Tables: php bin/engeen queue:table writes a migration for jobs, failed_jobs, idempotency_keys and audit_events.
  • Worker: php bin/engeen queue:work --queue=webhooks,default. SIGTERM finishes the current job first. A job over its timeout kills the worker (needs pcntl) and is retried later.
  • Failed jobs: queue:failed, queue:retry <id|all>, queue:forget <id>, queue:flush.
  • The current tenant is stored with the job and restored by the worker.
  • Idempotency::once('key', fn () => …) and the Idempotent middleware use Idempotency::store() (cache by default, DatabaseIdempotencyStore for several hosts).

Console, migrations and scheduler

Copy stubs/bin/engeen to bin/ and stubs/config/console.php to config/. Run php bin/engeen list to see every command.

// config/console.php
return [
    'commands' => [App\Console\Commands\RefreshTokens::class],
    'schedule' => function (Schedule $s): void {
        $s->command('tokens:refresh')->everyMinutes(5)->withoutOverlapping();
        $s->job(new SyncMenus())->hourly();
        $s->call(fn () => (new DatabaseIdempotencyStore())->prune())->dailyAt('03:30')->timezone('America/Santiago');
    },
];
  • Commands extend Exhaust\Console\Command ($signature, $description, handle(): int).
  • Migrations: make:migration create_orders_table --create=orders, migrate, migrate:status, migrate:rollback [--step=N]. Files return new class extends Exhaust\DB\Migrations\Migration and use $this->schema().
  • Scheduler: one cron line * * * * * php bin/engeen schedule:run, or schedule:work as a container process.
  • Generators: make:controller [--api], make:model [--tenant], make:job, make:command, make:middleware. Also route:list, route:check, route:cache, route:clear, db:seed, config:cache, config:clear and tenancy:audit.
  • Leave built-in commands out with 'disable' => ['migrate', 'migrate:*', 'make:migration', 'db:seed'] in config/console.php (fnmatch patterns), or $kernel->disable(...) before withDefaults(). An app command with the name of a built-in one (e.g. its own migrate) replaces it.

Outgoing HTTP and OAuth2

$tokens = new ClientCredentials('https://auth.uber.com/oauth/v2/token', $clientId, $clientSecret, scope: 'eats.order', cacheKey: "uber:{$storeId}");

$uber = Http::client()
    ->baseUrl('https://api.uber.com/v1/eats')
    ->withOAuth($tokens)          // cached token, one process renews it, renewed once on 401
    ->retry(3, 500)              // 429/5xx/connection errors, honors Retry-After
    ->timeout(10)
    ->withLogger(Log::channel('integrations'));   // secrets redacted

$order = $uber->get("/orders/{$id}")->throw()->json();

It runs on the curl extension, with no extra dependency. Use Http::fake([...]) in tests. DriverManager registers named adapters ($platforms->extend('uber', fn () => new UberAdapter(...))).

Multitenancy

class Order extends Model
{
    use \Exhaust\Tenancy\BelongsToTenant;   // const TENANT_COLUMN = 'empresa_id' (default)
}

Tenant::set($empresaId);       // or the ResolveTenant middleware
Order::all();                  // WHERE orders.empresa_id = ?
Order::allTenants()->count();  // deliberate cross-tenant query

A query on a tenant model with no tenant set throws instead of returning every company's rows. New rows get the tenant automatically, and changing it is refused. php bin/engeen tenancy:audit lists models whose table has the column but no trait.

Encryption and secrets

  • Crypt::encrypt() / decrypt() (AES-256-GCM). Keys come from APP_KEY=kid:base64:…, and old keys stay readable through APP_KEYS_OLD, which allows rotation.
  • Eloquent casts Security\Casts\Encrypted and EncryptedArray. Add the HidesEncryptedAttributes trait to leave them out of toArray().
  • Redactor::redact($array) masks tokens, passwords and signatures. JsonLogger and the HTTP client use it.

Environment, configuration and logging

// bootstrap.php
Exhaust\Config\Env::load(APP_ROOT, required: ['APP_ENV', 'APP_KEY', 'DB_PASSWORD']);   // fails early with the missing list
$conf = Exhaust\Config\Config::load(APP_ROOT . '/config/config.php', APP_ROOT . '/storage/cache/config.php');

env('DB_HOST', 'localhost');
config('health.enabled', true);      // dot notation over app()->conf

Log::configure(['channels' => ['webhooks' => ['path' => 'storage/logs/webhooks.log']]]);
Log::channel('webhooks')->info('Order {id} received', ['id' => $id]);   // one JSON line, with request_id and tenant
AuditLog::record('uber.order.created', $request->json(), reference: $eventId, raw: $request->rawBody());

Required variables are opt-in. APP_ENV is optional: Env::load() does not define it, so env('APP_ENV') is null when it is not set, while Env::environment() and Env::isProduction() treat it as production. List it in required to make it mandatory; a value outside Env::ENVIRONMENTS always fails.

Define APP_ROOT in public/index.php and bin/engeen (define('APP_ROOT', dirname(__DIR__));) so Support\Paths resolves the same root from the web server and the CLI; the config stubs build every path with Paths::base().

Keep secrets in .env or the container environment only, and never commit them.

Testing helpers

final class UberWebhookTest extends TestCase
{
    use \Exhaust\Testing\InteractsWithHttp;

    public function test_webhook(): void
    {
        Queue::fake();
        [$headers, $body] = $this->signed('secret', ['event_id' => 'e1'], 'X-Uber-Signature');

        $this->http('POST', '/webhooks/uber', $headers, $body)->assertStatus(202)->assertJsonPath('status', 'queued');
        $this->assertCount(1, Queue::pushed(ProcessUberOrder::class));
        $this->assertTenantScoped(Order::class);
    }
}

Exceptions in http() become the error answer with debug on. By default the body is JSON (text on raw routes) whatever the headers, as in 1.1; set protected bool $negotiateErrorFormat = true; in the test to get the production format (commands for X-Requested-With, curtains for Accept: text/html, ...).

InteractsWithDatabase::migrateFresh($connection, $path) rebuilds a test database. Fakes: Queue::fake(), Http::fake(), ArrayCache.

Docker

stubs/docker/ has a reference Dockerfile, an entrypoint.sh (creates storage/ owned by www-data, optional RUN_MIGRATIONS=1 and CACHE_CONFIG=1) and a supervisord.conf that runs Apache, the queue worker and the scheduler. When a storage directory is not writable, the app fails with a message naming the directory and the PHP user, instead of a generic 500.

Template engines

Configured in config/config.php → template_engine.use. All engines share the same rendering API.

app()->render('folder/template.html.twig', ['user' => $user]);
Config key Engine
twig Twig — recommended for production
smarty Smarty
piston Piston — built-in, PHP-native, no compilation
plates Plates
blade Blade (via illuminate/view)

Running tests

./vendor/bin/phpunit --display-warnings

# Slow groups, excluded by default
./vendor/bin/phpunit --group integration --display-warnings   # php -S + curl (session lock and cookies)
./vendor/bin/phpunit --group performance --display-warnings   # router timings

# With HTML coverage report (requires Xdebug)
XDEBUG_MODE=coverage ./vendor/bin/phpunit --coverage-html coverage/