Controllers
Inject data into a view at render time.
A controller is a PHP file that runs just before a view renders. It receives $app, $page and the context merged so far, and returns an array that is merged into the template's variables. Use one for data every page of a view needs: related pages, navigation, computed values.
Controllers are view-scoped and run only while a page renders. Route handlers and guards fetch their own data.
Location
Colocated with the view's template and router. Optional.
site/views/{view}/controller.php
phlat/views/{view}/controller.php ← framework-shipped views (e.g. admin)
Structure
Return a callable that returns an array:
<?php
use Phlat\App;
use Phlat\Page;
return function (App $app, Page $page, array $context): array {
$posts = $app->page('blog')
->children('published=1, sort=-created');
return compact('posts');
};
The keys become template variables:
{foreach $posts as $post}
<a href="{$post->url()}">{$post->title}</a>
{/foreach}
Layers
Page::render() merges two layers, in order:
- The global controller,
views/controller.php(view nameapp). It runs for every page. - The page's own view controller.
The view controller receives the global result as $context, and its own keys win on collision. Nothing else merges automatically. To use another view's data, call $page->controller('otherView', $context).
Phlat ships no global controller. A site defines whatever its layouts need.