HelloWorld Module Walkthrough
The complete HelloWorld module — routing, views, security attributes, and input handling in one self-contained example.
Beginner
The HelloWorld module ships inside Zero Framework's core, at core/modules/HelloWorld/, as a reference implementation. It demonstrates the most common patterns you will use in every module you build: public endpoints, authenticated endpoints, permission-protected endpoints, variadic arguments, and input sanitization.
It is an example module, and core/Modules.php leaves example modules off until the site turns them on. To try it, add one line to app/modules.ini:
[enabled] HelloWorld = on
Then open /hello-world. See Bundled Modules for the other modules core ships.
Every code block below is the actual HelloWorld source. Nothing has been simplified or trimmed for the tutorial.
1 The Module Structure
Like every Zero module, HelloWorld follows a predictable directory layout. The controller class name matches the directory name, and assets are organized by type:
There is no route file and no registration step. Once the module is on, a class in the right directory is all the framework needs. A module you write yourself goes in the site's modules/ folder and is on by default.
toolbar-test.php has no method behind it. When a module has no method for an endpoint, Response::__call() looks for a view file of that name in the module's view/ folder and renders it, so /hello-world/toolbar-test works anyway.
2 The Controller
Here is the complete HelloWorld.php controller. Read through it first, then we will break down each section:
<?php
namespace Zero\Core\Module;
use \Zero\Core\Attribute\{AllowedMethods, RequireAuthLevel, RequirePermission};
class HelloWorld extends \Zero\Core\Module
{
/**
* Index endpoint - shows links and descriptions of other endpoints
* Only responds to GET requests
*/
#[AllowedMethods('GET')]
public function index()
{
$this->respond($this->viewPath . "index.php");
}
/**
* Say hello endpoint
* - No args: "hello world!"
* - Single arg: "Hello, {arg}!"
* - Multiple args: "Hello, {arg1, arg2, and arg3}!"
* Responds correctly to Accept: application/json header
*/
public function sayHello(...$names)
{
$this->data = [
'greeting' => $this->buildGreeting($names)
];
$this->respond($this->viewPath . "sayHello.php");
}
/**
* Secure hello endpoint - requires authentication
* Same behavior as sayHello but for authenticated users only
*/
#[RequireAuthLevel(1)]
public function secureHello(...$names)
{
$this->data = [
'greeting' => $this->buildGreeting($names)
];
$this->respond($this->viewPath . "secureHello.php");
}
/**
* Permitted hello endpoint - requires authentication and "allow.hello.world" permission
* Same behavior as sayHello but with permission check
*/
#[RequirePermission('allow.hello.world')]
public function permittedHello(...$names)
{
$this->data = [
'greeting' => $this->buildGreeting($names)
];
$this->respond($this->viewPath . "permittedHello.php");
}
/**
* Build the greeting string based on arguments
*
* @param array $names Array of name strings
* @return string The formatted greeting
*/
private function buildGreeting(array $names): string
{
// No arguments - default greeting
if (empty($names)) {
return "hello world!";
}
// Sanitize all inputs
$names = array_map(function($name) {
return htmlspecialchars(trim($name), ENT_QUOTES, 'UTF-8');
}, $names);
// Filter out empty strings
$names = array_filter($names, fn($name) => $name !== '');
if (empty($names)) {
return "hello world!";
}
$count = count($names);
if ($count === 1) {
// Single name: "Hello, Name!"
return "Hello, {$names[0]}!";
}
if ($count === 2) {
// Two names: "Hello, Name1 and Name2!"
return "Hello, {$names[0]} and {$names[1]}!";
}
// Three or more: "Hello, Name1, Name2, and Name3!"
$lastIndex = $count - 1;
$lastItem = array_pop($names);
$list = implode(', ', $names);
return "Hello, {$list}, and {$lastItem}!";
}
}
Let us walk through each part.
Namespace and Imports
namespace Zero\Core\Module;
use \Zero\Core\Attribute\{AllowedMethods, RequireAuthLevel, RequirePermission};
HelloWorld is bundled with core, so its namespace is Zero\Core\Module. A top-level module in your site's own modules/ folder uses Zero\Module. The three attribute imports give us HTTP method restriction, authentication level checks, and named permission checks. These are applied declaratively on each method.
The index() Method
#[AllowedMethods('GET')]
public function index()
{
$this->respond($this->viewPath . "index.php");
}
The simplest possible endpoint. #[AllowedMethods('GET')] rejects POST, PUT, and other methods with a 405 Method Not Allowed response. The respond() call renders the view inside the site frame (header, footer, navigation).
Note the use of $this->viewPath — this is set automatically by the framework to point to the module's view/ directory. Always use this property instead of hardcoding paths.
The sayHello() Method
public function sayHello(...$names)
{
$this->data = [
'greeting' => $this->buildGreeting($names)
];
$this->respond($this->viewPath . "sayHello.php");
}
This method is completely public — no attributes, so anyone can call it with any HTTP method. The ...$names variadic parameter captures all remaining URL segments as an array. Visiting /hello-world/say-hello/alice/bob passes ['alice', 'bob'] into $names.
Data is passed to the view by setting $this->data. Response::build() includes the view file from inside the module object, so the view reads the same property: $this->data['greeting'].
3 Three Security Levels
The HelloWorld module demonstrates three access tiers, each building on the last:
| Method | Access Level | Attributes |
|---|---|---|
sayHello() |
Public — anyone can call it | None |
secureHello() |
Authenticated — must hold an auth level | #[RequireAuthLevel(1)] |
permittedHello() |
Permitted — must be logged in and hold a specific permission | #[RequirePermission('allow.hello.world')] |
Authenticated Endpoint
#[RequireAuthLevel(1)]
public function secureHello(...$names)
{
$this->data = [
'greeting' => $this->buildGreeting($names)
];
$this->respond($this->viewPath . "secureHello.php");
}
RequireAuthLevel(1) means the caller must hold an auth.level of at least 1. Anonymous visitors get a 401 Unauthorized. The business logic is identical to sayHello() — the only difference is the attribute.
This endpoint predates the ruling and still carries a bare level gate, which is why it appears here. Do not copy it into new code — use #[RequirePermission], and never pair the two. RequireAuthLevel is the one gate that does not enforce a verified email, and a level gate beside a permission gate silently vetoes the grant. See Attributes.
Permission-Protected Endpoint
#[RequirePermission('allow.hello.world')]
public function permittedHello(...$names)
{
$this->data = [
'greeting' => $this->buildGreeting($names)
];
$this->respond($this->viewPath . "permittedHello.php");
}
One attribute, two checks. RequirePermission::handler() opens by running RequireLogin's check, so the user must be logged in and hold the allow.hello.world permission. If both pass, the method runs normally. What a refused caller gets depends on what it asked for:
| Caller | Browser request | Accept: application/json |
|---|---|---|
| Not logged in | Redirect to /user/login |
401 |
| Logged in, permission missing | Redirect to /auth/access-request/permission |
403 |
Both redirect targets belong to bundled modules: /user/login to User, the access-request page to Auth. They answer 404 on a site that turned those modules off.
Permissions are granted in the database, not in code. See Permissions.
You can stack as many attributes as you need. They run in declaration order, class level before method level, and the first one that refuses ends the request. Attributes lists the order to declare them in.
4 Input Handling
The buildGreeting() private method handles all the input processing. It is a good example of defensive coding in a framework that passes raw URL segments to your methods:
private function buildGreeting(array $names): string
{
// No arguments - default greeting
if (empty($names)) {
return "hello world!";
}
// Sanitize all inputs
$names = array_map(function($name) {
return htmlspecialchars(trim($name), ENT_QUOTES, 'UTF-8');
}, $names);
// Filter out empty strings
$names = array_filter($names, fn($name) => $name !== '');
if (empty($names)) {
return "hello world!";
}
$count = count($names);
if ($count === 1) {
// Single name: "Hello, Name!"
return "Hello, {$names[0]}!";
}
if ($count === 2) {
// Two names: "Hello, Name1 and Name2!"
return "Hello, {$names[0]} and {$names[1]}!";
}
// Three or more: "Hello, Name1, Name2, and Name3!"
$lastIndex = $count - 1;
$lastItem = array_pop($names);
$list = implode(', ', $names);
return "Hello, {$list}, and {$lastItem}!";
}
Key patterns to note:
- Private, not public — The dispatcher calls
$module->{$endpoint}()from outside the object, so every public method of a module is an endpoint. A helper isprivateorprotected, which keeps/hello-world/build-greetingfrom routing to it - Empty check first — If no names are provided, fall back to a default greeting
- Sanitize everything — Every name is run through
htmlspecialchars()withENT_QUOTESandUTF-8encoding to prevent XSS - Filter blanks — After trimming, empty strings are removed so double slashes in URLs don't create ghost entries
- Natural language formatting — One name, two names, and three-or-more names each get grammatically correct output with Oxford comma handling
URL segments arrive as raw strings. They are not automatically sanitized by the framework. Always sanitize before using them in output, database queries, or any other context.
5 The View Files
View files are included from inside the module object, so $this is in scope and the data the endpoint set is at $this->data. Here is a typical HelloWorld view:
<main class="container">
<div class="greeting-display">
<p class="greeting"><?= $this->data['greeting'] ?></p>
</div>
<p class="back-link"><a href="/hello-world">Back to HelloWorld index</a></p>
</main>
The view is intentionally simple. It reads greeting from the $this->data array and prints it without escaping, which is safe here only because buildGreeting() already escaped every name. The framework wraps this in the site frame automatically — you don't need to include headers, footers, or navigation in your view files.
The secured views follow the same pattern, with a badge that says which gate was passed:
<main class="container">
<div class="greeting-display secure">
<span class="badge auth">Authenticated</span>
<p class="greeting"><?= $this->data['greeting'] ?></p>
</div>
<p class="back-link"><a href="/hello-world">Back to HelloWorld index</a></p>
</main>
The classes in these views are styled by assets/css/hello-world.css. core/Response.php loads a stylesheet when its filename matches the module or the endpoint, and adds ?v= with the file's modification time so browsers pick up a new copy after a deploy. See Assets.
If the request sends an Accept: application/json header, the same respond() call skips the view and the frame and returns JSON instead: $this->data under a data key, with status and code beside it. Every endpoint that calls respond() with a view path is a dual HTML/JSON endpoint.
6 URL Mapping
Here is how URLs map to method calls for the HelloWorld module:
| URL | Method Call | Access |
|---|---|---|
/hello-world |
index() |
GET only |
/hello-world/say-hello |
sayHello() |
Public |
/hello-world/say-hello/alice |
sayHello('alice') |
Public |
/hello-world/say-hello/alice/bob |
sayHello('alice', 'bob') |
Public |
/hello-world/secure-hello |
secureHello() |
Auth level 1+ |
/hello-world/secure-hello/alice |
secureHello('alice') |
Auth level 1+ |
/hello-world/permitted-hello |
permittedHello() |
Logged in & allow.hello.world |
/hello-world/permitted-hello/alice/bob |
permittedHello('alice', 'bob') |
Logged in & allow.hello.world |
Notice the pattern: kebab-case URLs map to camelCase methods, and each additional URL segment becomes a method argument. The variadic ...$names parameter captures any number of trailing segments.
7 Key Takeaways
The HelloWorld module demonstrates the core patterns you will use in every Zero Framework module:
- Convention over configuration — The module directory name, class name, and namespace follow a strict convention. No routing table or registration is needed.
- Declarative security — Attributes like
#[RequirePermission('allow.hello.world')]replace boilerplate authorization checks at the top of every method. - Variadic arguments — Use
...$argsto capture any number of URL segments. Use named parameters like$idwhen you expect a specific number. - Always sanitize input — URL arguments are raw strings. Run them through
htmlspecialchars()before output and use prepared statements for database queries. - Views are simple — Pass data with
$this->data, render with$this->respond(). The framework handles framing, asset loading, and JSON responses. - Public means routable — Every public method is an endpoint. Keep helpers
privateorprotected. - Progressive security — Start with public endpoints, then add authentication and permissions as needed by stacking attributes.
Now that you understand module basics, try the Counter Component tutorial to learn ShadowComponent, or read the Attributes documentation for the full list of available attributes.