Skip to content

API Reference

Mikhail Deynekin edited this page Oct 11, 2026 · 3 revisions

API Cheatsheet

Namespace HtmlPhp\. Identical in both editions. Everything instance-based; nothing reads globals. Full docblocks live in the source β€” this is the map.

Note

Canonical spec: docs/API.md.

Engine β€” the facade

$engine = Engine::create($configArrayOrObject, fn(Container $c) => …);
Method Returns Purpose
render(string $name, array $vars = [], ?RenderOptions $o = null) string locator-resolved template
renderFile(string $path, …) string host-trusted path (size-guarded, SSI-anchored)
renderString(string $source, …) string inline/DB templates
display(…) / displayString(…) void echo variants
processSsi(string $content, ?DocumentInfo $d = null) string standalone SSI pass
ssiVariables(?DocumentInfo $d = null) array<string,string> built-in SSI map
t / n / x / nx(…) string translations
setLocale(string) / locale() β€” active locale
loadTranslations(string $locale, ?string $domain) list<string> force-load i18n.paths
lint($nameOrPath) / lintString($src) / lintDirectory($dir) list<LintIssue> / map static validation
clearCache() int purge cache + parse memo
stats() ?RenderStats last render's profile
config() container() renderer() locator() ssi() translator() filters() events() cache() logger() diagnostics() clock() linter() escaper() service lazy singletons
version() string "5.0.0 (8.3 edition)"

Container & service ids

Engine::create($config, function (Container $c): void {
    $c->instance(Contracts\CacheInterface::class, new MyRedisCache());
    $c->instance(Support\ClockInterface::class, new FrozenClock(1700000000));
    $c->instance(Log\LoggerInterface::class, Log\Psr3Adapter::wrap($monolog));
    $c->instance(I18n\TranslatorInterface::class, new MyDbTranslator());
});

Ids are class names: Config::class Β· Contracts\CacheInterface::class Β· Log\LoggerInterface::class Β· Event\Dispatcher::class Β· Diagnostics::class Β· Support\ClockInterface::class Β· Html\Escaper::class Β· I18n\Formats::class Β· I18n\TranslatorInterface::class Β· Template\{Filters, TemplateLocator, Renderer, Linter}::class Β· Ssi\Processor::class Β· Engine::class. API: factory(id, fn) instance(id, $obj) get has service<T>() ids reset.

Value objects

Class Shape
Config (+9 group classes, 6 enums) immutable, fromArray/toArray/merge/with*, validates at construction
Template\RenderOptions readonly, all-nullable: file root request ssi structure autoEscape missingVar cache ttl locale ssiVars (+fromArray() migration aid)
Template\RenderStats template durationMs cacheHit substitutions loops loopRows conditionals includes sections translations ssiDirectives outputBytes peakMemoryKb templates[] (+ summary hook in the 8.5 edition)
Template\LintIssue readonly severity code message file line context + format()/isError()/toArray()
Ssi\DocumentInfo readonly file root request vars + forString()/withVars()
RequestContext readonly; fromServer($_SERVER) / cli($cwd) / http(name)
Scope push/pop/with/get/has/set/find/all/depth β€” dot paths over arrays, ArrayAccess, props, get*/is*/has* accessors; no globals fallback. v5 statics: Scope::step(value, path) (dotted walk) and Scope::index(value, key) (one dynamic key β€” arrays / ArrayAccess / UTF-8 string offsets only, never object props)

Events (tag β†’ payload)

Tag Kind Payload
htmlphp.render.before action origin, vars, renderContext
htmlphp.render filter text, origin, vars
htmlphp.render.after action origin, text
htmlphp.rendered action RenderStats
htmlphp.error action code, message, context
htmlphp.translate filter text, msgid, domain, locale
htmlphp.translate.miss action msgid, domain, locale
htmlphp.filter.apply action filterName, args
htmlphp.ssi.builtins filter built-in map
htmlphp.ssi.include_path filter resolvedPath, label
htmlphp.ssi.echo filter value, name

Dispatcher: on(tag, cb, prio=10): Closure(unsubscribe) Β· dispatch Β· filter (null keeps previous) Β· off/has/tags/reset.

Contracts & implementations

Contracts\CacheInterface { get set has delete clear(): int }
  β”œβ”€ Cache\FileCache (sharded, atomic, probabilistic GC, dir hardening)
  β”œβ”€ Cache\ApcuCache Β· ArrayCache Β· NullCache Β· Psr16Adapter
  └─ WordPress\WpCache (object cache + transients + key registry)

Log\LoggerInterface { log debug info notice warning error critical alert emergency }
  β”œβ”€ Log\FileLogger Β· ErrorLogLogger Β· SyslogLogger Β· ArrayLogger Β· NullLogger
  β”œβ”€ Log\Psr3Adapter (wraps Monolog & friends β€” no psr/log required)
  └─ WordPress\WpLogger

I18n\TranslatorInterface { t n x nx locale setLocale }
  └─ I18n\Translator (own implementation; WP delegation built in)

Support\ClockInterface { now dateTime }
  β”œβ”€ SystemClock └─ FrozenClock (tests/CLI)

Ssi\DirectiveInterface { name render(attrs, SsiContext) }

Exceptions

HtmlPhpException  (readonly context map, withContext(), describe())
β”œβ”€ ConfigException        β”œβ”€ ContainerException   β”œβ”€ IoException
β”œβ”€ CacheException         β”œβ”€ RegexException       β”œβ”€ SsiException
β”œβ”€ I18nException          └─ TemplateException
                              β”œβ”€ TemplateNotFoundException
                              └─ TemplateSyntaxException   (file + line in context)

Support utilities worth knowing

Class Highlights
Support\Str stringify (enum/Stringable-safe) Β· numericValue (intl formats) Β· round/cleanRound/number/divide Β· v5: power/sqrt (INF/NAN β†’ 0.0), accumulate (capped sum+count, MAX_AGGREGATE_ITEMS = 100 000) Β· truncate (word-boundary, mb) Β· slugify (deterministic: built-in map first, ICU fallback for unmapped scripts) Β· normalizeEntities Β· formatSize (Apache style) Β· isValidVariableName Β· sanitizeRecursive
Template\Expression closed interpreter behind @If/@Set/loop ranges/@Trans count and v5 inline %{= …}: evaluate/validate/truthy/reset, FUNCTIONS whitelist (23). Budgets: length, depth 32, AST memo 4 096 FIFO, iterable walks 100 000
Template\Substitution public statics for host tooling: splitFilters Β· v5: splitExpressionPayload (quote/bracket-aware) Β· splitArguments Β· parseSegments
Support\Pcre throwing wrappers (replace/replaceCallback/split), degrading match/matchAll, replaceUnicode, isValid
Io\Files / AtomicWriter / PathGuard capped slurp Β· temp+verify+rename writes Β· realpath containment + extension deny-lists
Html\Escaper html attr url json js css byStrategy sanitizeArray; subclassable/replaceable
Html\Cleaner cleanHtml (allow-list, script/style removal) Β· normalize Β· lcTags Β· trimSpaces
Input all()/source() β€” sanitised superglobal copies (the sanctioned edge)
I18n\{Extractor, Auditor, Formats} POT extraction w/ references Β· missing/unused audit Β· locale number/date/ago

WordPress namespace

WordPress\Bridge (boot/engine/booted/reset) Β· TemplateLoader Β· Shortcodes Β· WpCache Β· WpLogger Β· AdminPage Β· Cli Β· Mailer Β· Maintenance\{Nonces Options Transients Notices Db Cron Logs SystemInfo Updates Health Assets Rest} β†’ WordPress Integration

Clone this wiki locally