Plugins
Run code at five fixed points of every request without touching core. A plugin is one class in the site's plugin/ folder.
Overview
A plugin is the file plugin/{Name}/{Name}.php, declaring the class \Zero\Plugin\{Name}, which extends the abstract base class \Zero\Plugin. There is no registry and no configuration: Zero\Core\PluginLoader (core/PluginLoader.php) finds the plugins on each request and Application calls their hooks.
Core ships the loader and the five hook points, nothing else. The base class is plugin/Plugin.php, which travels with the plugin folder (core/docs/PLUGINS.md). A site with no plugin/ folder loads no plugins and pays nothing for the system; stave.dev is one.
Lifecycle Hooks
| Hook | When It Fires | Available State |
|---|---|---|
afterAutoloaders() |
End of registerAutoloaders(), right after the plugins are loaded |
Zero's and Composer's autoloaders, ZERO_ROOT, MODULE_PATH, the session |
afterParseRequest() |
End of parseRequest() |
Request::$module, $Module, $endpoint, $args, $method |
afterConstants() |
End of defineConstants() |
Every .ini constant |
beforeRun($module, $endpoint, $args) |
In run(), after the module class is resolved and before it is constructed |
The three arguments run() was given: module and endpoint as the URL named them, and the remaining URL segments |
afterRun($module, $endpoint, $args) |
End of run(), after the endpoint returned or its HTTPError was rendered |
The same three arguments; the response is in the output buffer, not yet sent |
Full Lifecycle Sequence
new Application() output buffering on, session started │ registerAutoloaders() ├─ autoloaders registered, Composer's vendor/autoload.php loaded ├─ PluginLoader::load() discovers all plugins └─ afterAutoloaders() hook fires │ parseRequest() ├─ Request populated with module/endpoint/args └─ afterParseRequest() hook fires │ defineConstants() ├─ .ini files read └─ afterConstants() hook fires │ run($module, $endpoint, $args) ├─ ban check, module check, disabled account logged out ├─ module class resolved ├─ beforeRun() hook fires ├─ module constructed ├─ attributes checked ├─ endpoint called └─ afterRun() hook fires │ Application::__destruct() └─ Output buffer flushed to browser
It does not fire when the request ends before run() returns: an endpoint or attribute that calls exit (after a redirect, for example), a banned request, or run() stopping at its module check.
Creating a Plugin
Create a directory and PHP file in plugin/ that matches the plugin name:
Extend the \Zero\Plugin base class and override only the hooks you need:
<?php
namespace Zero\Plugin;
use \Zero\Plugin as BasePlugin;
use \Zero\Core\Console;
class MyPlugin extends BasePlugin {
/**
* Priority: lower runs first (0-100, default 50)
*/
protected int $priority = 50;
public function afterConstants(): void {
Console::debug("MyPlugin loaded, DEVMODE = " . (defined('DEVMODE') && DEVMODE ? 'true' : 'false'));
}
public function beforeRun(string $module, string $endpoint, mixed $args): void {
// Runs before the endpoint method is called
}
public function afterRun(string $module, string $endpoint, mixed $args): void {
// Runs after the endpoint completes
}
}
That's a complete plugin. It is loaded on the next request.
Example: Request Logger
<?php
namespace Zero\Plugin;
use \Zero\Plugin as BasePlugin;
class RequestLogger extends BasePlugin {
protected int $priority = 20;
private float $startTime;
private string $logFile;
public function afterAutoloaders(): void {
$this->startTime = microtime(true);
$this->logFile = ZERO_ROOT . 'storage/logs/requests.log';
}
public function beforeRun(string $module, string $endpoint, mixed $args): void {
$entry = sprintf(
"[%s] START %s::%s() from %s\n",
date('Y-m-d H:i:s'), $module, $endpoint, \Zero\Core\Request::clientIp()
);
file_put_contents($this->logFile, $entry, FILE_APPEND);
}
public function afterRun(string $module, string $endpoint, mixed $args): void {
$elapsed = round((microtime(true) - $this->startTime) * 1000, 2);
$entry = sprintf(
"[%s] END %s::%s() [%sms]\n",
date('Y-m-d H:i:s'), $module, $endpoint, $elapsed
);
file_put_contents($this->logFile, $entry, FILE_APPEND);
}
}
Plugin API Reference
The base class is plugin/Plugin.php; this is its interface as core/docs/PLUGINS.md documents it.
Base Class Properties
| Property | Type | Description |
|---|---|---|
$priority |
int |
Execution priority, 0–100. Lower runs first. Default: 50. |
$cacheDir |
string |
Public. Set by PluginLoader::load() to storage/cache/plugin/{Name}/. |
Lifecycle Methods
All default to no-op. Override only the hooks your plugin needs, with exactly these signatures:
public function afterAutoloaders(): void {}
public function afterParseRequest(): void {}
public function afterConstants(): void {}
public function beforeRun(string $module, string $endpoint, mixed $args): void {}
public function afterRun(string $module, string $endpoint, mixed $args): void {}
Cache Helper Methods
A hook runs on every request, so cache anything expensive. The helpers are protected. An entry is the file storage/cache/plugin/{PluginName}/{key}.json; its age is the file's modification time, and storage/cache/ must be writable by the web server user.
| Method | Description |
|---|---|
cacheGet(string $key, int $ttl = 3600): mixed |
Read from cache. Returns null if missing, older than $ttl seconds, or not valid JSON; a stale or invalid entry is deleted. |
cacheSet(string $key, mixed $data): void |
Write to cache, creating the folder when missing. $data must be JSON-serializable. |
cacheClear(string $key): void |
Delete a cache entry. |
getPriority(): int |
Public. This plugin's priority value. |
public function afterConstants(): void {
// Try cache first (1 hour TTL)
$data = $this->cacheGet('mydata', 3600);
if ($data === null) {
// Cache miss - do expensive operation
$data = $this->expensiveOperation();
$this->cacheSet('mydata', $data);
}
// Use $data
}
Priority and Ordering
Every hook runs the plugins in priority order: lower numbers run first. Ties are broken by class name (PluginLoader::load()). The 0–100 scale is a convention:
| Range | Purpose | Examples |
|---|---|---|
0–20 |
Early initialization | Timers, logging setup |
20–40 |
Request processing | Routing, validation |
40–60 |
Normal operations | Default plugins (priority 50) |
60–80 |
Late processing | Navigation, UI assembly |
80–100 |
Output modification | HTML injection, compression |
How plugins are found
PluginLoader::load() runs once per request, at the end of registerAutoloaders():
- Returns no plugins when
ZERO_ROOT/plugin/is not a directory. - Requires
plugin/Plugin.php. - For each subfolder
{Name}that holds{Name}.php: requires the file and constructs\Zero\Plugin\{Name}. A subfolder without that file is skipped silently. - Sets the plugin's
$cacheDir. - Sorts by priority, then class name.
Two mistakes are logged as warnings and the plugin is left out: the file exists but the class \Zero\Plugin\{Name} does not, and the class does not extend \Zero\Plugin.
DevToolbar and SideNav
core/docs/PLUGINS.md describes two plugins. Both live in the plugin/ folder, not in core/, so a site has them only when its plugin folder does.
| Plugin | Purpose | Priority | Hooks Used |
|---|---|---|---|
| DevToolbar | Debug toolbar showing performance, request, and session data, in DEVMODE only. DEVMODE is not defined at present (Development Mode), so it stays off |
10 | afterAutoloaders(), afterConstants(), beforeRun(), afterRun() |
| SideNav | Discovers modules, views, and submodules to build navigation | 70 | afterConstants() |
What core does carry is the data a toolbar reads, available to any plugin:
| Call | Gives |
|---|---|
Database::enableQueryTracking(), Database::getQueries() | Each statement the request ran, with parameters, time and row count (Models & Database) |
Console::getMessages() | Every log message of the request, whatever the threshold (Security & Logging) |
Application::$attributeLog | Each attribute checked: its name, class, method or call scope, and target (Attributes) |
Error Handling in Plugins
PluginLoader::hook() catches anything a hook throws, logs it as an error and goes on to the next plugin. A hook that throws never breaks the request:
foreach ($plugins as $plugin) {
try {
$plugin->$hook(...$args);
} catch (\Throwable $e) {
// Plugins must never break the framework
$name = get_class($plugin);
Console::error("Plugin {$name}::{$hook}() threw: " . $e->getMessage());
}
}
A syntax error in a plugin's file, or a constructor that throws, breaks every request. Keep constructors empty and do the work in a hook.
Disabling Plugins
The loader only sees {Name}/{Name}.php, so any of these takes a plugin out:
# Rename the file mv plugin/MyPlugin/MyPlugin.php plugin/MyPlugin/MyPlugin.php.disabled # Or rename the directory mv plugin/MyPlugin plugin/_MyPlugin # Or delete it entirely rm -rf plugin/MyPlugin
The change takes effect on the next request.
Plugin vs. Attribute
Both plugins and attributes add behavior to the request cycle, but they serve different purposes:
| Concern | Plugin | Attribute |
|---|---|---|
| Scope | Framework-wide, every request | Per-endpoint or per-class |
| Purpose | Lifecycle concerns (timing, logging, discovery) | Endpoint concerns (auth, validation, sanitization) |
| Can block requests? | No. A hook cannot stop the others, and blocking is an attribute's job | Yes — it runs before the endpoint and can end the request |
| Configuration | Zero — drop in a file | Declarative — add attribute to method |
| Examples | Request logging, navigation discovery, debug toolbar | #[RequireLogin], #[AllowedMethods('POST')], #[Sanitize] |
If it applies to every request, use a plugin. If it applies to specific endpoints, use an attribute.