Skip to content

Working With Agents

This page is for AI coding agents (Claude Code, Cursor, Codex, Aider, etc.) and contributors who need a deeper map of the framework internals than How To Contribute provides. If you're getting started, read that first.

Repository layout

Path What lives there
src/ Framework source — Composer-loaded into every ZubZet project
src/IncludedComponents/ Bundled controllers, models, views, routes, and migrations the framework ships
docs/ MkDocs-rendered documentation (this site)
tests/e2e/ Cypress end-to-end test suite running the dockerized app
tests/e2e/modules/ The two sample modules (guestbook, theme) permanently installed in the e2e app
mkdocs.yml Docs site nav and theme config
composer.json PHP 8.0–8.6 support, autoload, dependencies

Testing has two layers. What needs the running application (web server, database, browser, console process) is tested end-to-end from tests/e2e/. Logic that needs none of that has unit tests in tests/unit/: PHPUnit for src/ (composer test) and Mocha and Chai for web/Z.js, the same pair Cypress specs are written in (npm install once, then npm test in tests/unit/js/). A new Z.js test is a *.test.js file anywhere under tests/unit/js/. Like a Cypress spec it imports nothing: describe, it, expect, a fresh Z per test and the $.ajax() stand-in ajax are globals, provided by tests/unit/js/support/setup.js. In CI the e2e job only starts after the unit tests passed.

src/ subdirectories at a glance:

  • Authentication/ — User, Session, Permission/, PasswordHash/ (native Argon2id, self-describing schemes, rehash-on-login), role and group handling
  • Bootstrap/ — Configuration trait that parses z_settings.ini
  • Console/ — CLI application bootstrap, run action bridge, ActionDiscovery and CommandDiscovery
  • Core/ — Foundation traits (CanRetrieveModel, CanRetrieveBooterSettings, Constants, FunctionConflictResolution)
  • Database/ — Connection, prepared-statement Interaction, migration commands
  • ErrorHandling/ — ExceptionBehavior, WhoopsHandler, BehaviorOption, DebugBar/ (bridge, collectors, traits)
  • Form/ — Validation rules (required, unique, exists, length, …)
  • Logger/ — LoggerFactory, channels, slow-request logging
  • Maintenance/ — Standalone maintenance gate (see Maintenance Mode)
  • Message/ — Request, Response, Input/State
  • QueryBuilder/ — CakePHP query-builder adapter
  • Registry/ — Central resolver for convention lookups + module discovery (see below)
  • Resources/ — Asset proxy: ordered Mount chain, bundled Composer packages
  • Routing/ — Router trait, FastRoute integration, Route builder
  • Security/ — CSRF (the header-based check Router::execute() runs first, returning whether the request is verified; the router answers a rejected one with the error/403 page; GET, HEAD and OPTIONS are skipped unless an action opts back in with Request::csrfBlockAdditionalMethod()); Secrets/: Encryption (versioned zenc:<cipher>: values, key from the encryption_key setting), Cipher/ (Cipher interface, AesGcmCipher), DecryptionException
  • Support/ — Global helpers, dynamic attributes, function-conflict resolution
  • Testing/ — Coverage commands

Bootstrap order

src/ZubZet.php __construct is sensitive to ordering. The current sequence:

Collector::initialize();          // coverage, only when .coverage.session exists
self::$instance = $this;           // zubzet() resolves to this
new GlobalReferences;              // defines config(), logger(), isCli(), …
new Constants;                     // TIMESPAN_DAY_1 etc.
$this->loadConfiguration(...);     // populates settings from z_settings.ini

MaintenanceHandler::gate();        // exits early if maintenance is active

LoggerFactory::handleSlowRequest();
$this->setExceptionBehavior();
$this->assetProxy = new AssetProxy;
new Helpers;
$this->setRequestResponse(...);
$this->z_db = new Connection;         // connects lazily on the first query
DebugBarBridge::bootstrap();
$this->user = new User;

A few inter-phase dependencies that are not obvious:

  • The config() helper resolves through zubzet(), which requires both self::$instance = $this and new GlobalReferences to have run. Anything calling config() must be after both.
  • Configuration (the trait at src/Bootstrap/Configuration.php) is genuinely self-contained — no DB, no logger, no instance lookups. Safe to invoke before any other subsystem.
  • setExceptionBehavior() reads $this->showErrors, which loadConfiguration populates. Calling them in the wrong order means Whoops never installs.
  • LoggerFactory::handleSlowRequest() just calls register_shutdown_function(…). PHP fires shutdown handlers even after exit;, so anything that exits before this point cleanly bypasses logger side-effects. MaintenanceHandler::gate() relies on this — a maintenance hit performs zero DB writes and no log writes.
  • BehaviorOption levels: 0 = NONE, 1 = EXCEPTIONS, 2 = ALL (src/ErrorHandling/BehaviorOption.php).

Routing & MVC

ZubZet uses convention-based routing with FastRoute as an opt-in override. The path ["dashboard", "stats"] maps to DashboardController->action_stats($req, $res). Default action is action_index; missing methods fall to action_fallback. Controller and model files resolve through the Registry (see below): flat lookup first, then recursively into subdirectories by bare name, across userspace, modules, and framework roots. Model dot notation (getModel("reports.Stats")) addresses an exact sub-path and never falls back to the recursive index. See MVC, Controllers and Actions, and Routing.

A view is a Blade template that extends a layout and defines head/content sections:

@extends($layout)

@section("head")
    <link rel="stylesheet" href="...">
@endsection

@section("content")
    <h1><?= $opt["title"] ?></h1>
@endsection

Rendered via $res->render("path/to/view", $vars, "layout/…") or the view() global helper.

Registry & modules

src/Registry/ is the single resolver for everything the framework loads by convention (controllers, models, views, routes, commands, migrations, seeds, assets). The API is three static calls on Registry: paths($kind) (ordered roots), files($kind) (every file across roots), and find($kind, $name) (locate one file). Precedence everywhere: userspace, then modules in order, then framework. Asset-proxy mounts follow the same order (modules before the framework layers); the application's webroot needs no mount because the web server serves it before PHP runs.

find() memoizes per request in InternalRuntimeCache and probes each root flat first; the recursive per-root index (RootIndex) only runs for bare names after a flat miss, shallowest match first. Do not add new file_exists/glob lookups at call sites: route them through the Registry.

Module discovery lives in Registry\Modules: installed Composer packages of type zubzet-module, ordered by the modules ini key (comma-separated package names), unlisted ones after in Composer installed order, individually deactivatable via modules_disabled. Convention console commands (app/Commands/, userspace and modules) are discovered by Console\CommandDiscovery and added in reverse precedence order because Symfony resolves command-name collisions last-add-wins: the userspace registration lands last and wins. The sample modules are tests/e2e/modules/{guestbook,theme}, exercised by the specs in tests/e2e/tests/cypress/e2e/modules/. User-facing docs: Modules; internals and rationale: Module System Architecture.

Render engine (Katana)

Views render through Katana, a standalone Blade compiler. It is Blade only, with no closure fallback. The user-facing reference is Views.

The only Katana-specific glue is src/Rendering/Katana/:

  • Engine.php is the adapter. It registers the view roots from Registry::paths("views") as an ordered finder chain (userspace z_views first, then module view roots in module order, then framework IncludedComponents/views), so a name resolves by precedence and @extends / @include / components all resolve across every root. It builds a fresh Blade per render so @section state cannot leak between renders, registers the framework essentials under the zubzet component namespace (<x-zubzet::head/> and <x-zubzet::body/>, which an app component can neither shadow nor be shadowed by), and hands the layout name over as the $layout render datum.
  • Hooks.php binds request-scoped directives, currently @auth and @guest. The argument is a framework permission (dotted, wildcard aware), and @guest is the negation. This is where future framework directives go.

src/Rendering/CanRenderView.php builds the $opt contract, logs the render and feeds the debug bar, then renders through the engine. A missing view or layout is caught (BladeException) and re-rendered as the framework 500 page in the guaranteed layout/min_layout. View names resolve by name (a legacy .php or .blade.php extension is stripped; dot and slash notation both work), and the compiled-view cache directory is keyed on the installed engine reference so an engine upgrade starts from a clean cache. e() (in src/Support/Helpers.php) delegates to \Blade\e(), so it escapes identically to {{ }}.

Global helpers

Defined in src/Support/GlobalReferences.php, wrapped with FunctionConflictResolution::requireAndThen so they can't be redeclared. Helpers with a generic name that an application may already define (__(), deprecated()) use optionalAndThen instead and yield to the existing declaration:

Helper Returns
zubzet() ZubZet singleton
request() Current Request
response() Current Response
config($key=null, $useDefault=true, $default=null) Booter setting value, or array of all settings
configNumeric($key, $default) Booter setting as int, throwing on a non-numeric value
configSwitch($key, $default) Booter setting as bool (true/on/yes/1, false/off/no/0/empty), throwing on anything else. Never read a switch with config(): the text false is truthy
user() User (currently logged-in)
db($connection="default") Connection
model($name, $dir=null) Model instance
view($document, $opt=[], $options=[]) Renders via response
logger($name=null) Logger (default: app channel)
encryptSecret($plaintext) / decryptSecret($encrypted) Encrypted / decrypted value, throws DecryptionException on a wrong key
isCli() php_sapi_name() === "cli"
deprecated($version, $message) Nothing; raises an E_USER_DEPRECATED notice

See Global Helper Functions.

Deprecating behavior

When a code path has to keep working for existing projects but should no longer be used, keep it working and call deprecated() on that path.

  • $version is the framework version the deprecation starts in, the one the current Changelog.md section is for.
  • $message names what is deprecated and what to use instead, in one sentence. The caller sees it in the exception or log entry, so it has to be enough to fix the call site without opening framework code.
  • Call it right before the deprecated path does its work, not at the top of the method, so the supported paths stay silent.
  • The notice follows the showErrors contract like a PHP deprecation: 2 promotes it to an exception so development setups fail loudly, 1 logs it as a DEPRECATION event, 0 is silent.
  • When a whole method is retired, add a @deprecated since <version> docblock tag as well, so IDEs flag the callers. The tag alone cannot target a single branch, which is what the helper is for.
  • Mention the deprecation in Changelog.md as a migrator note.

Because the e2e app runs with showErrors = 2, a probe that exercises a deprecated path on purpose switches the mode off around the call and back on afterwards:

zubzet()->setExceptionBehavior(0);
echo(json_encode($this->getSession($session)));
zubzet()->setExceptionBehavior(2);

To assert the log entry instead, use mode 1 inside an output buffer, since that mode also displays the notice; see SessionController::action_legacyTokenDeprecated().

Testing

The full e2e suite lives in tests/e2e/. Run it from there:

cd tests/e2e

# Bring up the docker stack (~2 min first time)
npm run start

# Run the full suite headless (~9 min, 760+ tests)
npm run tests

# Just the module-system group
npm run tests -- --spec 'tests/cypress/e2e/modules/**/*.cy.js'

# Run one spec
npm run tests -- --spec 'tests/cypress/e2e/core/maintenance.cy.js'

# Open Cypress UI
npm run cypress

# Tear down
npm run stop

The dockerized app is served on http://localhost:8080. The host value in tests/e2e/z_config/z_settings.ini says :4000 — that's the configured base URL, not what Apache exposes. Always hit :8080 for manual checks.

Useful Cypress helpers in tests/e2e/tests/cypress/support/commands.js:

Command Purpose
cy.query(testid) Select by [data-test=…]
cy.fillForm(inputs) Bulk-fill a form
cy.loginAs(profile) Set session token from fixtures/logins.json
cy.setConfigSetting(key, value) Patch tests/e2e/z_config/z_settings.ini
cy.saveConfigBackup() / cy.restoreConfigBackup() Wrap suites that mutate config
cy.dbSeed() db:seed (optional exclude / include selectors) + clear sessions
cy.http(method, endpoint, body, callback) API call with X-API-KEY: 1234

To exercise a CLI command end-to-end:

cy.exec('docker exec application php index.php info:startup', {
    failOnNonZeroExit: false
}).then((result) => {
    expect(result.exitCode).to.equal(0);
});

Manual verification against a config-dependent path:

cp tests/e2e/z_config/z_settings.ini /tmp/zsettings.bak
sed -i 's/^maintenance_mode = .*/maintenance_mode = enabled/' tests/e2e/z_config/z_settings.ini
curl -s -o /tmp/page -w 'HTTP %{http_code}\n' http://localhost:8080/
cp /tmp/zsettings.bak tests/e2e/z_config/z_settings.ini

Several docker stacks side by side (the framework's and a customer project's) are fine. Cypress is the memory hog: one Cypress run at a time on a machine, never several in parallel, which ends in an OOM kill.

Debug bar

User-facing docs: Debug Bar.

All debug-bar code lives in src/ErrorHandling/DebugBar/:

  • DebugBarBridge.php is the only static entry point. It bootstraps StandardDebugBar, registers collectors, wires the asset proxy, and exposes renderHead() / renderBody() for the layout. It returns early when execution_type !== "test".
  • Collectors/ holds the framework's own collectors (QueryCollector, TemplateCollector, MonologCollector).
  • CanCollect is a trait used by the bridge to expose strongly typed collectQuery() / collectTemplate() / collectLogger() static helpers that forward into the right collector.
  • CanFormatValue is a small trait that normalizes scalars/arrays/objects into a readable string for display.

Call sites that feed the bar:

Source Trait/Helper Collector
Connection::exec DebugBarBridge::collectQuery(...) QueryCollector
CanRenderView::render DebugBarBridge::collectTemplate(...) TemplateCollector
LoggerFactory::getOrCreateLogger DebugBarBridge::collectLogger(...) MonologCollector (a Monolog handler)
Registry::find / Registry::files DebugBarBridge::collectResolution(...) ResolutionCollector (lookup provenance: userspace / module / framework)

Internal-query filtering uses source tagging: models that mark themselves with the IsInternalModel trait set isInternalModel = true, and only Model::exec() sets Connection::$callingModel before the query runs; Connection::exec hands it to the collector with every query. QueryCollector::addQuery then drops queries from internal models when debugbar_hide_internal_queries = true (default). The tag is never reset, so a later direct db()->exec(...), execQuery() or getFullTable(), getTableWhere() and countTableEntries() call reuses the previous model's tag (null at request start).

To add a new collector, implement DebugBar\DataCollector\DataCollector (or extend an existing one), register it in DebugBarBridge::bootstrap(), and expose a collectXxx() method on CanCollect that forwards via self::collect("name", "addXxx", func_get_args()).

Console commands

Run commands inside the application container:

docker exec application php index.php <command>
Command What it does
db:migrate Run pending migrations
db:seed Drop and re-seed the database
db:sync Sync migration state up to a version/date
db:status Show the migration lock state (exit 0 unlocked, 1 locked)
db:unlock-migration Release a stuck migration lock
repair:database-collation Convert the z_ tables to Connection::COLLATION; --include-app-tables adds the app tables and the database default
run Execute a controller action from the console
install Build a new project in an existing, writable folder
auth:migrate-hashing Wrap legacy password hashes in an Argon2id layer (onion)
info:startup Print framework startup banner (no side effects — safe in tests)
module:setup Append-only merge of missing module ini defaults into the app ini
testing:coverage:start / :stop Bracket a coverage session

Convention commands from app/Commands/ (userspace and modules) appear next to these in list; each is a global class named like its file, extending the Symfony Command class. On a command-name collision the userspace copy wins, then modules in order, then the framework.

See Console Commands for full flags.

Commit & PR conventions

  • Conventional commits with a scope: feat(admin): …, fix(layout): …, refactor(maintenance): …, test(...), docs(...). See How To Contribute for the migration from Gitmoji.
  • Atomic commits. Split work by scope. Example: a feature touching code + tests + docs becomes refactor(...), feat(...), test(...), docs(...) — four commits, one scope each. Combining (feat+test) is not the project style.
  • One-line messages, no Co-Authored-By trailer.
  • PR base is develop. Feature work merges into develop; develop is later promoted to main via a separate PR. Verify with gh pr view <n> --json baseRefName if unsure; some tooling surfaces stale branch names. See How To Contribute → Branching model.
  • CI runs e2e on PHP 8.0 and 8.6 for PRs and feature-branch pushes (the version-edge smoke). Pushes to develop, main, and version tags run the full matrix (8.0–8.6). Watch with gh pr checks <n> --repo zubzet/framework --watch.

Working style for AI agents

  • Never commit or push without an explicit ask. This is critical framework code. AI output is reviewed by hand before it lands — leave changes uncommitted in the working tree (or staged, if helpful) and wait. Even after a successful test run, do not run git commit, git push, or gh pr write actions unless the maintainer asks for them in that turn.
  • Iterative pace. Make small changes, run tests, report concisely, wait. Don't pre-build large structures unless asked.
  • Watch for parallel edits. A <system-reminder> notice that a file was modified means re-read it before any further change — never assume your in-context view is current.
  • "Any other ideas?" is a request for 3–4 ranked options with trade-offs and a recommendation. Don't implement until asked.
  • "Make a useful decision." Decide. State trade-offs in 1–2 lines, implement.
  • Inline aggressively. When a private function has only one caller, inlining is the project default. Drop dead code and unused parameters confidently.
  • Run the full e2e suite after any framework-internals change. Three minutes catches the kind of subtle ordering bugs that bootstrap-adjacent changes cause.
  • Compatibility is the first rule. Consumer projects run on this code. Before changing a public API, check how the real projects use it; the e2e app under tests/e2e/app is user code and must never need a change for a framework feature to work. A change that would break an existing app ships only together with a version migrator step.
  • A new setting travels as a set, in one PR. The key lands in stubs/project/z_config/z_settings.ini, in tests/e2e/z_config/z_settings.ini, in the migrator (CONFIG_<KEY> overrides apply only to keys the ini already has), in the docs and in Changelog.md. This is why everything lives in one repository.
  • Global helper names are specific. encryptSecret(), never encrypt(): the helpers live in the global namespace of every project, so a generic name collides sooner or later.

Migrations

Framework migrations live in src/IncludedComponents/database/Migration/ and ship with the framework. Project migrations live in app/Database/migrations; module migrations join the run as part of the external set (like the framework's). Executed state is keyed on the basename, so db:migrate/db:sync abort on duplicate basenames anywhere in the assembled set: prefix module migration filenames with the module name. See Migrations for the file/filename conventions and CLI commands.

Bundled migrations must be idempotent. They may already be partially applied on consumer projects (manual schema work, partial sync state, replays after a recovery) and re-running must not fail. Concretely:

  • CREATE TABLE IF NOT EXISTS …
  • ALTER TABLE … ADD COLUMN IF NOT EXISTS …
  • ALTER TABLE … ADD INDEX IF NOT EXISTS … (and the DROP variants)
  • INSERT … ON DUPLICATE KEY UPDATE or guarded with WHERE NOT EXISTS

The z_migration table (with z_migration_lock) prevents re-execution under normal flow, but the rule still applies — a migration that fails on second run is a bug.

Installer

docs/setup/install.sh writes the project's composer.json, runs composer require zubzet/framework in the project folder inside the PHP image, then runs bin/install from that vendor. bin/install is a standalone Symfony Console entry for the install command (src/Support/Commands/Install.php) that copies stubs/project around the vendor without booting the framework and never overwrites an existing file. The command is not registered in the framework's own console.

Version migrator

migrator/ holds the upgrade tool, one class per framework version (migrator/src/Version/V1_3_0.php); the steps of a postponed release merge into the earlier version class.

  • Only mechanical file changes through its own primitives (FileContent, shouldChangeIfIncludes, demandChange, the modifiers in migrator/src/Modifiers/). No raw scandir, is_dir or rmdir in a version class, as little logic as possible. It never runs database migrations and prints no hints; those belong in the upgrade guide.
  • --dry is absolute. A dry run changes nothing on disk, ever, and prints exactly what the real run would do.
  • Every step is idempotent. Running the same upgrade twice, or on a project that already has part of it by hand, changes nothing the second time and never fails.
  • A missed upgrade case is fixed in the migrator, not by making framework code tolerate the old shape.
  • Test a change in dry mode and for real against the e2e app (reset its files afterwards) and against at least one real old project.

Common pitfalls

  • Port confusion. App is at :8080, not :4000. The host setting in INI is informational, not the listening port.
  • Logic belongs in a unit test, not behind a probe controller. tests/unit/php/ (PHPUnit, namespace Tests\, one test class per class in src/, same path) and tests/unit/js/ are for everything whose result is a return value, an exception or the state of an object. A Cypress spec in tests/e2e/ is for what needs the web server, the database, the browser, a real process or more than one request. Do not add a controller to the e2e app that only calls a framework function and prints the result.
  • Tests\TestCase provides the framework to a unit test. bootFramework([...]) gives zubzet(), config() and the other global helpers an instance that holds exactly the given settings, without a config file, a database or a request. input() is an empty input state to fill with its with...() methods (its REQUEST is put together as GPC whatever the machine's request_order says, input("GP") picks another order), request() and response() make one current, currentUser() sets a user that needs no database, temporaryDirectory() and inDirectory() cover files, assertThrows() checks the exact class and message. Everything is reset after each test. A test class never writes its own boot. The constant FRAMEWORK_ROOT (from tests/unit/php/bootstrap.php) is the folder of the framework, for a test that has to name one of its files, instead of counting ../.
  • exit ends PHPUnit silently. Code that reaches exit or die (most of Response::success(), error(), reroute()) stops the whole run with exit code 0 and no summary: the remaining tests never run and CI stays green. Such code stays in e2e. header() does nothing on the CLI, so sent headers and status codes cannot be asserted in a unit test either. Code that calls header() or setcookie() still needs @runTestsInSeparateProcesses, because PHP refuses both once PHPUnit has printed anything.
  • Real HTTP requests in a unit test. Tests\Message\Input\StateHttpTest starts PHP's built-in web server on a free port with fixed php.ini settings and compares what State::fromRequest() holds with PHP's own $_GET, $_POST, $_COOKIE, $_FILES, $_REQUEST and body. Use it for anything that depends on what a client really sends (bodies, uploads, headers, request_order); a superglobal filled by hand only proves what the test assumed.
  • Multiple PHP versions in CI. The floor is PHP 8.0, the ceiling the newest line. Known breakers: #[\Override] does not exist before 8.3; implicit nullable parameters (string $x = null) are deprecated since 8.4, write ?string $x = null; finfo_close() is deprecated on the newest line; by-ref model constructors were removed in 1.2.
  • config() is unavailable before bootstrap. Anything called from MaintenanceHandler::gate() must already have configuration loaded; anything earlier must read INI directly.
  • A red CI run is classified first: a flake, a rebase side effect, or a real regression. Reproduce on the base branch before blaming your change. Local green is not CI green: CI runs PHP 8.0 and 8.6 on fresh volumes. Flakiness is never acceptable: a test that fails sometimes is fixed (deterministic app state, retrying assertions, proper waits), never re-run until green.
  • The sample modules are part of the e2e app. tests/e2e/modules/{guestbook,theme} are installed on every run; a red modules/ spec usually means a Registry or precedence regression, not a spec problem. Never "fix" one by renaming sample files to dodge a collision.
  • Convention classes are global. Controllers, models, and commands from userspace and modules share one global class namespace; the first include wins and class_exists guards prevent redeclaration fatals. Name module classes with a module prefix unless shadowing is intended.