Views & Responses
One endpoint can answer a browser with a page and an API client with JSON. core/Response.php decides from the request's headers.
View Files
Views are plain PHP files stored in modules/MyModule/view/. They have full access to $this — the module instance — so any properties you set on the controller are available directly in the template:
<?php
namespace Zero\Module;
class MyModule extends \Zero\Core\Module {
public function index() {
$this->title = 'Dashboard';
$this->items = ['Alpha', 'Bravo', 'Charlie'];
$this->respond($this->viewPath . 'index.php');
}
}
<h1><?= $this->title ?></h1>
<ul>
<?php foreach ($this->items as $item): ?>
<li><?= htmlspecialchars($item) ?></li>
<?php endforeach; ?>
</ul>
View files are loaded with include inside the Response class, which is why $this refers to the module instance and why a view can call the protected helpers. There is no separate template engine — it is just PHP.
Three Kinds of Request
| Request | Detected by | Gets |
|---|---|---|
| HTML | Anything else | The view wrapped in the frame |
| JSON | Request::$acceptsJSON: the Accept header names a JSON type |
JSON only. build() does nothing, so no view and no frame |
| AJAX | Request::$madeWithAJAX: X-Requested-With: XMLHttpRequest |
The view without the frame |
Response Methods
All of these are protected methods of Response, which Module extends. A controller and its views call them as $this->...; a URL cannot reach them (see Routing).
| Method | Purpose | Behavior |
|---|---|---|
respond($viewOrData, array $extra = []) |
Primary response method | JSON request → given a view file, exports $this->data; given anything else, exports thatHTML request → build()s the view |
build($view = "") |
HTML render | Prints head and header, the view, then sideNav and footer. $view is a file to include; a string that is not a file is printed as the page body. Does nothing for a JSON request, or when the response is already built. |
export($data = null, array $extra = []) |
JSON output | Prints the JSON envelope with Content-Type: application/json, whatever the Accept header. Does not exit. |
success($message, $data = []) |
Success after a write | JSON request → exports and exits HTML request → returns (so redirect can follow) |
error($message, $data = []) |
Failure after a write | JSON request → sets the HTTP status to $data['code'] or 400, exports and exitsHTML request → returns (so form can re-render) |
An endpoint that returns without building anything still gets a page: Response::__destruct() calls build() with $this->body, or an empty body.
JSON Response Envelope
export() wraps what it is given:
{
"data": { ... },
"status": "unknown",
"code": 200
}
| Key | Value |
|---|---|
data |
$data when it is an array, merged with $this->data when that is set |
message |
$data when it is a non-empty string, with tags stripped |
anything in $extra |
Merged at the root of the response |
status |
$extra['status'], else $this->status, else "unknown" |
code |
$extra['code'], else $this->code, else 200. This is a field of the body; export() does not set the HTTP status. |
The output is pretty-printed when DEVMODE is defined and true. It is not defined at present (Development Mode), so the JSON is compact.
When using respond() with a dual-purpose endpoint, $this->data is wrapped inside the envelope's "data" key — it is not at the root of the JSON response. Always unwrap the envelope client-side.
success() and error() pass their fields to export() as $data, so they are nested too:
{
"data": {
"success": true,
"message": "Article created",
"id": 7
},
"status": "unknown",
"code": 200
}
error($message) is the same with "success": false and "error": $message. The body of a thrown HTTPError is a different shape: see Error Handling.
Dual HTML/JSON Endpoints
A single method serves both an HTML page and a JSON API depending on the request's Accept header:
public function index() {
// Set $this->data — this is what JSON clients receive
$this->data = [
'articles' => $this->model->getAll(),
'count' => $this->model->count(),
];
$this->status = 'success';
// respond() checks the Accept header:
// JSON → exports $this->data as {"data": {"articles": [...], "count": 5}, ...}
// HTML → renders the view (which can also use $this->data)
$this->respond($this->viewPath . 'index.php');
}
Client-side, unwrap the envelope to access your data:
fetch('/article', {
headers: { 'Accept': 'application/json' }
})
.then(r => r.json())
.then(res => {
// res.data contains your $this->data payload
// res.status and res.code are envelope metadata
const articles = res.data.articles;
const count = res.data.count;
});
An endpoint that only ever answers JSON calls $this->export($data) directly.
The Frame System
When build() renders an HTML response, it wraps the view inside a frame made up of four pieces:
| Frame File | Purpose |
|---|---|
head.php |
Opening <html> and the <head> with its stylesheets |
header.php |
Site header and navigation |
sideNav.php |
Side navigation panel, printed after the view |
footer.php |
Site footer, scripts, closing </body> and </html> tags |
Where each piece comes from
Each piece is looked up on its own. Response::framePiecePath() returns the first of these that has the file:
- the module's
frame/folder ($this->framePath); for a submodule with none, the nearest ancestor's - the module's
view/folder ($this->viewPath) - the site's frame folder,
app/frontend/frame/(VIEW_PATH) - core's own copy in
core/skeleton/frontend/frame/
So a site needs no frame files to start with, overrides a piece by having the file, and a module that ships only frame/head.php still gets the site's header, side nav and footer. A piece that exists nowhere is skipped with a warning in the log. Each piece is included once per response.
Partials
A frame or a view finds any other file the same way. framePiecePath() returns null when no folder has it, so include the result only when there is one. This is how core's head.php lets a site add its own scripts and fonts:
<?php
if ($headScripts = $this->framePiecePath('_head-scripts')) {
include $headScripts;
}
?>
Core's skeleton holds four partials: _head-scripts, _oauth-brand, _oauth-buttons and _google-signin. A site replaces one by putting a file of that name in app/frontend/frame/.
Frame Overrides
A module provides its own frame files in a frame/ directory:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title><?= $this->title ?? 'My Module' ?></title>
<!-- Custom head content here -->
<link rel="stylesheet" href="/css/custom-theme.css">
<!-- IMPORTANT: Call these to preserve auto-loading -->
<?php $this->getStylesheets(); ?>
<?php $this->getScripts(); ?>
<?php $this->getComponents(); ?>
</head>
<body>
If you override head.php, you must include $this->getStylesheets(), $this->getScripts(), and $this->getComponents(), there or in the footer. Nothing else calls them, so without these calls the module's CSS, JS and components do not load.
Asset Loading Methods
| Method | Output |
|---|---|
$this->getStylesheets() |
<link> tags for the files in the module's public css/ folder named after the module or the endpoint |
$this->getScripts() |
<script> tags for the matching files in js/ |
$this->getComponents() |
Includes every .html file of the site's app/frontend/www/shadow-component/components/, then of the module's assets/component/, in alphabetical order |
Each tag carries the file's modification time as ?v=, so a changed file is fetched again. A module can override any of the three: core/AdminResponse.php overrides getStylesheets() and getScripts() to print admin assets inline. Assets has the naming convention; ShadowComponent covers components.
Hooks around the view
build() calls beforeView() between the header and the view and afterView() between the view and the side nav. Both are empty in Response; override them to print something on every page of a module. AdminResponse prints its breadcrumbs that way.
Borrowing Another Module's Frame
A module reachable from anywhere, such as a profile page, can render in the frame of the module that linked to it. Call adoptFrameFrom() in the constructor, before parent::__construct():
public function __construct() {
$this->adoptFrameFrom($_SERVER['HTTP_REFERER'] ?? null);
parent::__construct();
}
adoptFrameFrom(?string $url): bool sets $this->framePath and returns true only when all of these hold; otherwise it changes nothing and the module keeps its own frame:
- the URL's host is this site's host;
- its first path segment, lowercased, is only letters, digits and hyphens;
- that segment names a module that is switched on and has a
frame/folder.
The referer is client-controlled, which is why it only ever selects an existing folder. With no referer (a bookmark, a typed address, a privacy setting) the module falls back to its own frame.
AJAX Requests
When a request carries X-Requested-With: XMLHttpRequest, the frame pieces are skipped. Only the view content is returned, which suits loading partial HTML into an existing page.
// Returns only the view HTML, no frame wrapper
const response = await fetch('/article/show/42', {
headers: { 'X-Requested-With': 'XMLHttpRequest' }
});
const html = await response.text();
document.getElementById('content').innerHTML = html;
View-Only Endpoints
If a module has no method for a requested endpoint but has a matching view file, the framework renders it. This is useful for static content pages within a module:
Visiting /docs/about renders view/about.php without needing an about() method on the controller. The view still has access to $this and the full frame wrapping. The module's class attributes still apply; a view file has no method to put its own on. Routing has the full order of what answers a URL with no method, standalone pages included.