Creating Modules
A module is one folder: a controller, and next to it the views, models, assets and config that feature needs. Put the folder in modules/ and its URLs exist.
Scaffold One with mkmod
core/modules/Module/ is the reference module: a working example of every folder a module can have. The mkmod script in that folder copies from it to start a new module. Run it from the site root:
core/modules/Module/mkmod Inventory # controller, view, css, js, .gitignore core/modules/Module/mkmod Inventory --model --admin # add model/ and Admin/ core/modules/Module/mkmod Inventory --submodule=Reorder # nest a submodule core/modules/Module/mkmod Inventory --all --dry-run # show the full tree, write nothing core/modules/Module/mkmod # no name: prompt for each directory core/modules/Module/mkmod --help
With no flags it writes Inventory.php, view/index.php, assets/css/inventory.css, assets/js/inventory.js and a .gitignore. Each flag adds a folder:
| Flag | Adds |
|---|---|
--model | model/{Name}Model.php |
--frame | frame/head.php |
--admin | Admin/: controller, admin-config.php, view, assets |
--config | config.ini, config/example.ini, their blank copies in config-tmpl/, and strings/example.ini |
--aux | aux/nav.php |
--helper | helper/ExampleHelper.php |
--component | assets/component/{name}-panel.html |
--submodule=<Name> | submodule/{Name}/ |
--tests | tests/{Name}Test.php |
--all | Every folder above |
- The new module goes into the site's
modules/folder, never intocore/.--dest <dir>writes somewhere else. mkmodrefuses a name a bundled module incore/modules/already has (mkmod Authexits 1), the nameModule, and a module that already exists unless you pass--force. Names are compared ignoring case and hyphens. A site module that overrides a bundled one is written by hand.
The name
A folder in modules/ is a module when its name matches ^[A-Z][A-Za-z0-9]*$: a leading capital, then letters and digits (Modules::isModuleDirName() in core/Modules.php; mkmod applies the same rule). Inventory, HelloWorld and ApiDemo are modules. A folder named hello_world or Links (old) is not, and the router never serves it.
A site's own module is on as soon as its folder exists. Bundled Modules covers the modules core ships and how app/modules.ini switches any module off.
Anatomy of a Module
Only the controller is required. Core reads each of the other folders when it is there:
| Path | What core does with it | More |
|---|---|---|
{Name}.php |
The controller. The class name matches the folder name, in namespace Zero\Module, extending \Zero\Core\Module. |
Routing |
view/ |
$this->viewPath. Endpoint templates, with $this in scope. view/error{code}.php is used by Response::renderError(). |
Views, Errors |
frame/ |
$this->framePath. The module's own head, header, sideNav or footer; a piece it does not have comes from the site's frame. |
Views |
model/ |
$this->modelPath. Classes in namespace Zero\Module\{Name}\Model load without a require. |
Models |
lib/ |
Classes in namespace Zero\Module\{Name}\Lib, for other modules to call. |
Below |
assets/css/, assets/js/ |
Linked into the web root at /assets/{name}/, the module name lowercased, by Module::__construct(). {module}.css loads on every endpoint, {endpoint}.css on that endpoint only; the same for .js. |
Assets |
assets/component/ |
Component .html files, included by Response::getComponents(). |
ShadowComponent |
config.ini, config/*.ini |
Every key becomes a constant, on requests for this module (Application::loadModuleConfig()). |
Configuration |
strings/*.ini |
The module's wording as constants, each defined unless the site's app/strings/ already defined it. |
Configuration |
aux/ |
$this->getAuxiliary('nav') in a frame includes aux/nav.php of the module serving the request, when it has one (Module::getAuxiliary()). |
|
submodule/ |
Child modules, resolved by Module::__call() when the parent has no matching method. |
Submodules |
Admin/ |
A {Name}Admin class and admin-config.php. The Admin module lists it as a card on /admin. |
Admin |
Anything else in the folder is yours. core/modules/Module/README names the common conventions that nothing in core reads: helper/ (plain classes you require yourself), tests/, docs/, template/, data/, and config-tmpl/, the committed blank copies of config files that are themselves not committed.
Controller Class
Every public method of the controller is an endpoint, and URL segments arrive as its arguments. Everything else is protected or private: see Routing.
<?php
namespace Zero\Module;
use Zero\Core\Request;
use Zero\Core\Exception\HTTPError;
use Zero\Core\Attribute\AllowedMethods;
use Zero\Core\Attribute\RequiredParams;
use Zero\Core\Attribute\RequireLogin;
use Zero\Module\Inventory\Model\ItemModel;
class Inventory extends \Zero\Core\Module {
private ItemModel $items;
public function __construct() {
parent::__construct();
$this->items = new ItemModel();
}
/**
* List all items
* GET /inventory
*/
public function index() {
$this->data = ['items' => $this->items->all()];
$this->respond($this->viewPath . 'index.php');
}
/**
* Show a single item
* GET /inventory/show/42
*/
public function show($id) {
$item = $this->items->find($id);
if (!$item) {
throw new HTTPError(404, 'Item not found');
}
$this->data = ['item' => $item];
$this->respond($this->viewPath . 'show.php');
}
/**
* Create a new item
* POST /inventory/create
*/
#[RequireLogin]
#[AllowedMethods('POST')]
#[RequiredParams(['name'])]
public function create() {
$id = $this->items->create($_POST['name']);
$this->success('Item created', ['id' => $id]); // a JSON client stops here
Request::redirect('/inventory/show/' . $id);
}
}
ItemModel is the module's own class in model/ItemModel.php; its methods here are the example's, not the framework's. Models covers what a model can be built on.
A module in modules/UserProfile/ has a class named UserProfile in UserProfile.php. The framework finds the controller by that name, and the URL for it is /user-profile.
Response helpers
A controller answers with the protected methods it inherits from core/Response.php:
| Call | Use it to |
|---|---|
$this->respond($view) |
Render the view for a browser, or send $this->data to a JSON client |
$this->build($view) |
Render HTML only |
$this->export($data) |
Send JSON only |
$this->success($message), $this->error($message) |
Answer a JSON client after a write and stop; do nothing for a browser, so the redirect or the form follows |
throw new HTTPError($code, $detail) |
End the request with an error page or a JSON error |
Views & Responses has the signatures and the JSON shapes; Error Handling covers HTTPError.
Auto-Defined Paths
When a module is instantiated, Module::defineBasePaths() sets these properties. A folder the module has gets the module's path; otherwise the property points at the site-wide folder.
| Property | Module Path | Fallback Path |
|---|---|---|
$this->viewPath |
modules/Inventory/view/ |
app/frontend/view/ |
$this->framePath |
modules/Inventory/frame/ |
A submodule: the nearest ancestor's frame/. Then app/frontend/frame/ |
$this->modelPath |
modules/Inventory/model/ |
app/frontend/model/ |
Reference views as $this->viewPath . 'index.php' instead of hardcoding paths. The same line then works in a module, in a submodule, and in a module that lives in core/modules/.
Sharing Logic Between Modules: lib/
Logic that another module uses lives in the providing module's lib/ folder: modules/{Name}/lib/{Class}.php, in namespace Zero\Module\{Name}\Lib. Other modules call a module's lib/, never its model/, so the provider's rules apply wherever its data changes. In core, Zero\Core\Module\Push\Lib\PushHelper (core/modules/Push/lib/PushHelper.php) is how any module sends a push notification.
<?php
namespace Zero\Module\Inventory\Lib;
class Stock {
// Takes the acting user as an argument rather than reading the session
public function reserve(int $itemId, int $userId): bool {
// ...
}
}
use Zero\Core\Session; use Zero\Module\Inventory\Lib\Stock; // No require: the namespace says where the file is $reserved = (new Stock())->reserve($itemId, Session::userId());
Autoloading has the rule that maps the namespace to the file. Libraries covers the ones that belong to no module, in core/lib/.
What Makes a Good Module
core/docs/MODULE_PHILOSOPHY.md asks for utility and fun over complexity. Before writing a module:
- Will you, or others, use it regularly?
- Is the complexity justified by what it gives back?
- Are you solving a real problem, or going for impressive over useful?
- Is it fun to build and to use?
When in doubt, start simple. A module can always grow later.