Documentation MVC
Controllers
Classes, actions, passing data to views, JSON, redirects and 404.
Anatomy of a controller
A controller is a class that extends olala\controller. Its name and location are strictly defined:
- file:
site/modules/{module}/controllers/{controller}Controller.php; - class:
{Module}{Controller}Controller— both parts capitalized, no namespace; - actions are public methods with the
Actionsuffix.
<?php
use olala\controller;
class ShopCartController extends controller {
// /shop/cart
function indexAction() {
return $this->render('cart', ['items' => []]);
}
// /shop/cart/clear
function clearAction() {
// ...
header('Location: /shop/cart');
return '';
}
}The easiest way to create a controller is the console command — it makes both the class and a template:
./create controller shop cartWhat an action returns
An action must return a string — it becomes the page content and is inserted into the layout.
Don't print anything with echo: that output would end up above the layout.
return $this->render('template', [...])— an HTML page from a template;return 'Text'— just a string;return json_encode($data)— a response for JavaScript (together withview::ajax(), see AJAX).
The render() method
$this->render(string $view, array $vars = []): stringRenders a template and returns the resulting HTML. The template is looked up in this order:
site/modules/{module}/views/{view}.phpolala/modules/{module}/views/{view}.phpsite/layouts/{current layout}/{view}.php— handy for shared parts: headers, cards, the 404 page.
If the name starts with /, it's a path from the site root without .php: $this->render('/site/modules/blog/views/card').
Variables from the array are available in the template and are also passed to the layout. This makes it easy to set the page title right from the action:
return $this->render('show', [
'title' => $post['title'], // seen by both the template and the layout
'post' => $post,
]);Don't name template variables view, file or renderVars — those are local variables of render() itself, and your values will be ignored.
Input data
| Source | How to get it |
|---|---|
| Query string, route parameters | $_GET['id'] |
| A regular HTML form | $_POST['email'] |
| JSON in the request body (fetch) | $this->getData()['email'] — the body is decoded once and cached |
| A request header | router::getHeader('X-Token') |
Shared code for controllers
Controllers are ordinary classes, so shared logic is easy to move into a base class. Since the base class is loaded by the autoloader, it must have a namespace that matches its path:
<?php
namespace site\core;
use olala\controller;
use olala\modules\Session;
abstract class AdminController extends controller {
function __construct() {
$this->startSession();
if (!Session::get('user_id')) {
header('Location: /login');
die();
}
}
}<?php
use site\core\AdminController;
class AdminOrdersController extends AdminController {
function indexAction() {
return $this->render('orders');
}
}404 errors and redirects
There are two ways to say “not found”. The simple one is a core exception that immediately responds with a 404 code and plain text, without the layout:
use olala\exceptions\NotFoundException;
$post = Post::find($_GET['slug']);
if (!$post) throw new NotFoundException('Post not found');The nice one is to set the response code yourself and render your own template inside the layout:
if (!$post) {
http_response_code(404);
return $this->render('404', ['title' => 'Not found']); // site/layouts/default/404.php
}A redirect is just a header: header('Location: /catalog'); return '';
Built-in methods
| Method | What it does |
|---|---|
render($view, $vars) | renders a template and returns HTML |
getData() | the request body decoded from JSON |
startSession() | starts the session (Sessions) |
metaCheck($data) | simple form protection against bots: compares $data['meta'] with the robot_check value in the session and throws an exception on mismatch |