Extension Protocol (v1.11.0, protocol version 1.0)
This document is the written contract for the template engine's extension points: signatures, parameters, return values, lifecycle, hook timing, and stability guarantees for all three extension points. Third-party plugins should follow this protocol rather than reverse-engineering existing plugins. Protocol version constant:
Zandy_Template::ZTE_EXTENSION_PROTOCOL_VERSION.
1. The Three Extension Points
| Extension point | Registration | Purpose | Hook |
|---|---|---|---|
| Directive plugin | registerDirective($name, $handler, $position) |
Custom <!--{name ...}--> syntax |
before = before core compilation / after = on the compiled output |
| Filter plugin | registerFunction($name, $handler, $position) |
Custom {$var|name:param} filters |
same as above |
| Validator plugin | registerValidator($validator) |
Compile-time template validation (may halt) | pre stage (source template, runs exactly once per compile) |
Composer installation note: when installed via Composer,
autoload.filesincomposer.jsonloads all bundled plugins (template inheritance, macros, fragment cache, filters, debug-info, etc.) — they are always enabled; a manual install requires you torequire_oncethe plugin files you need. When writing custom plugins, assume the bundled ones are already present (duplicate registrations under the same name are ignored with anE_USER_WARNINGnotice).
$position: 'before' (default 'after') — before plugins process the source
template before core compilation (syntax preprocessing/transformation);
after plugins run on the compiled output string after core compilation
(custom directives take over there).
2. Directive Plugin Contract
Zandy_Template::registerDirective('my-tag', function ($content, $params, $context) {
return '<div class="my">' . $content . '</div>';
});Handler signature: function (string $content, string $params, array $context): string
| Parameter | Description |
|---|---|
$content |
Block body content (<!--{my-tag}-->content<!--{/my-tag}-->); empty string for single-tag form |
$params |
Tag parameters (a=1 from <!--{my-tag a=1}-->, trimmed); empty string if none |
$context |
Context array, fields below |
| Return value | String replacing the tag (and block body), inserted verbatim into the output |
Two matched forms (the same handler receives both):
- Block:
<!--{name params}-->content<!--{/name}-->→$content= inner content - Single:
<!--{name params}-->(not followed by<!--{/name}-->) →$content=''
Context fields:
| Field | Type | Description |
|---|---|---|
tplDir |
string | Template directory (normalized) |
cacheDir |
string | Cache directory (normalized) |
EOB |
string | Heredoc identifier for this compilation (use when generated code needs heredoc isolation) |
tplFileName |
string | Template file name (passed by the parse layer, may be empty) |
3. Filter Plugin Contract
Zandy_Template::registerFunction('my-filter', function ($value, $params) {
return 'my_php_func(' . $value . ', ' . var_export($params, true) . ')';
});Handler signature: function (string $value, string $params): string
| Parameter | Description |
|---|---|
$value |
Current expression string (in a chain, the previous filter's output expression) |
$params |
Raw text after the colon (50 in {$v|my-filter:50}; surrounding quotes stripped); empty string if none |
| Return value | Transformed PHP expression string (not final output — the engine wraps it in echo <return>;) |
Chain semantics: {$v|f1|f2:p} invokes handlers left to right, $value passed along.
Reserved names: raw (removes auto-escaping) and escape (explicit escaping)
are protocol-reserved; custom filters must not use them.
Argument wrapping convention (clarified in v1.12.0; used by all built-in on-demand plugins):
The engine splits name from params at the first :, and strips surrounding
quotes only when the entire parameter string is quoted. Handlers therefore
receive bare values and must wrap them back into valid PHP expressions:
| Parameter form | Convention | Example |
|---|---|---|
$-prefixed |
expression pass-through (no wrapping) | {$v|my-filter:$docroot} |
| Other bare values | plugin adds quotes to form a string literal | {$v|my-filter:on} → 'on' |
| Multiple params | comma-separated (bare : not allowed — swallowed by the first-colon rule) |
{$v|my-filter:3,4} |
| Arrays / complex expressions | passed through as-is ([-prefixed, no quote stripping) |
{$v|my-filter:["k"=>1]} |
Reference implementation (the built-in plugins' shared pattern):
$wrap = function($p) {
$p = trim($p);
if ($p === '') return "''";
if ($p[0] === '$') return $p; // expression pass-through
return "'" . addslashes(trim($p, "'\"")) . "'"; // string literal
};4. Validator Contract
Zandy_Template::registerValidator(function ($templateSource) {
if (strpos($templateSource, 'FORBIDDEN') !== false) {
Zandy_Template::halt('template contains forbidden content', true);
}
});Signature: function (string $templateSource): void
- Receives the source template (before compilation); call
Zandy_Template::halt($msg, true)on problems - Controlled by the
setValidationEnabled(false)master switch - Runs standalone even when only validators are registered (no before plugins) — v1.11.0 protocol fix
5. Lifecycle
Registration (process start / plugin file load)
→ parse() pre stages: before directive/function plugins process the source; validators run
→ structural scan (block-stack validation, plugin directive names exempt — unknown directives are opaque)
→ token compile core: unknown directives preserved verbatim
→ after plugin stage: custom directives/filters take over on the output
→ stage 13 fidelity escaping → fragment cache post-processing → artifact6. Stability Guarantees (protocol 1.x)
- Handler signatures, context field names, and hook timing are not changed incompatibly within 1.x
- New context fields are compatible changes (plugins must defensively
isset) - The reserved-name list (built-in directive/filter names) only grows — plugins must not register names colliding with built-ins
- Duplicate-registration guard: first registration wins (subsequent handlers silently ignored)
- Protocol versioning: incompatible changes bump the major version (2.0), compatible additions bump the minor
7. Introspection API
Zandy_Template::getRegisteredDirectives(); // array('before'=>[name=>handler], 'after'=>[...])
Zandy_Template::getRegisteredFunctions(); // same shape
Zandy_Template::getRegisteredValidators(); // array(callable, ...)
Zandy_Template::ZTE_EXTENSION_PROTOCOL_VERSION; // '1.0'8. Plugin Skeleton and Best Practices
A minimal runnable skeleton lives at plugins/skeleton.php (copy and rename to start). Best practices:
- Name prefixing: prefix plugin directive/filter names (
mytag-) to avoid collisions with built-ins and other plugins - Output escaping: user data in handler output must go through
htmlspecialchars(..., ENT_QUOTES, 'UTF-8') - halt diagnostics: on validation failure call
halt($msg, true)with enough context to locate the problem - Sandbox compatibility: never splice template attributes/arguments into PHP expressions raw — call
Zandy_Template::checkExpressionAllowed($expr, $line)first (it halts when sandbox/policy rejects) - Single-file distribution: a plugin is a single PHP file — require to register, no construction, no state
9. Sandbox and Plugin Boundary (v1.14.x)
The sandbox audits template source text only, never code generated by plugins. tpl_sandbox and
tpl_sandbox_policy check expressions and call surfaces in the host template at compile time; PHP code that a
plugin emits during the compile pipeline is not audited again. Two hard constraints follow:
- Plugins must be trusted: enabling a plugin means trusting its code. Only require plugin files from trusted sources — never load plugin files uploaded by users, delivered from a database, or writable by low-privilege roles.
- Never splice arguments into expressions raw: if a directive handler or filter treats an attribute value/argument as a PHP expression, it must re-check through the public entry first, then splice:
// Directive plugin: before using an attribute value as an expression
Zandy_Template::checkExpressionAllowed($expr, $line); // superglobals / dangerous constructs / policy whitelist
// Filter plugin: same for arguments used as expressions
Zandy_Template::checkExpressionAllowed($arg, $line);If a plugin produces dynamic file paths, it must perform its own boundary checks (isTemplatePathInTplDir(),
isCachePathSafe()); the sandbox does not replace filesystem boundary checks.
Variable injection in the sandbox is tightened as well: with tpl_sandbox enabled,
extractTemplateVars() injects only the caller's explicit $vars, never siteConf or globals (V2-09).