Repository navigation
Developer Guide Routing and Controllers
Developer Guide · First package · Views
Internals: HTTP, Router, RouteExecutor, Request, CSRF.
Register routes inside a RuntimeRouterAPI using addRouter(). The API injects the dispatcher and bootstrap later loads them into RouterManager. A route names a path, controller action and either a Controller or ObjectFactory. The manager uses insertion order and one registry key per route name; registering a duplicate name replaces that entry. Unnamed routes receive numeric names. Use unique names, especially when GET and POST share a URL.
Excerpt in the first tutorial's PageRoutes::main(), after retrieving $controllers:
$welcome = $controllers->getController('welcome');
$this->addRouter((new \router\Router('/hello/{name}', 'greet', $welcome))
->setName('demo.greet'));
$this->addRouter((new \router\Router('/hello', 'submit', $welcome))
->setMethod('POST')->setName('demo.submit'));Add greet()/submit() actions and their matching view files before using these routes. An action receives one captured-parameter array, not separate function parameters. Route actions must return View, Redirect or Response. Direct view rendering requires an initialized viewName/path, dispatcher, packageName, asset path and bundle; the controller runtime/factory supplies those in the tutorial.
Patterns match exactly by slash-delimited segments. A segment {name} captures one segment under that key. The default matcher does not constrain values, perform regex routing, decode captures, normalize trailing slashes, or support wildcards/optional segments. An empty segment can be captured. Request::path() strips the query string. Validate and decode values in your action as needed.
setMethod() normalizes alphabetic tokens, so GET, POST, PUT, PATCH, DELETE, OPTIONS, HEAD and other alphabetic tokens can be configured. Each route has one method. GET also accepts HEAD, with explicit HEAD routes preferred; the web bootstrap suppresses the HEAD body. A matching path with an unsupported method returns 405 and Allow; no matching path returns 404. OPTIONS is safe for CSRF but no automatic OPTIONS route is created.
For HTML forms, POST _method=PUT, PATCH or DELETE overrides the effective method. Other overrides are ignored. There is no automatic JSON body-to-controller parameter binding: use a request/body parser appropriate to your action. CLI bootstrap registers routes but does not execute an HTTP route.
Complete DemoSite/middleware/RequireAdmin.php:
<?php
namespace DemoSite\middleware;
use middleware\IMiddleware;
final class RequireAdmin implements IMiddleware
{
public function handle(): void
{
if (!isset($_SESSION['admin']['id'])) {
throw new \RuntimeException('Authentication required.');
}
}
}Excerpt where $route is an existing Router:
$route->addMiddleware(new \DemoSite\middleware\RequireAdmin());Ensure the session has started before this example's check. A route holds one middleware; another addMiddleware() replaces it. handle() receives no route/request/next arguments. Its return value is ignored by route execution: returning false or Response does not stop the pipeline. To stop, throw or use explicit redirect/termination behavior; compose multiple checks inside your middleware when needed.
Mutating methods require a valid token by default. Execution order is method validation → CSRF validation → middleware → lazy controller creation → context response registration → router.enter dispatch → action. Rejected method/CSRF requests do not run middleware or construct the controller.
Template excerpt inside an initialized Blade view:
<form method="post" action="/hello">
@csrf
<input name="message">
<button type="submit">Send</button>
</form>@csrf uses the framework's session-backed token manager, with _token as the default name. API clients may send X-CSRF-TOKEN. Request extraction gives the header priority, then POST _token, then URL-encoded raw body fields. It does not read tokens from arbitrary JSON bodies. Invalid or array-valued tokens fail validation with 403. A token uses 32 random bytes encoded as hex and hash_equals comparison. To prepare one before rendering, use (new \router\security\Csrf())->token(); regenerate() replaces it.
withoutCsrf() disables the guard for that route. Use it only for a deliberately alternate protection scheme such as an authenticated webhook with independent request verification. Route-level middleware is not a substitute for input validation. Secure session cookies require HTTPS, except when the local HTTP setting has been deliberately changed.
RouterManager exposes addRouter()/loadRouters(), getRoutes(), getRouteByName(), getRouteByPath(path, method) and startRouter(request). getRouteByPath() compares literal definitions, not pattern matches. router\facade\Router::make() delegates to an injectable IRouteFactory; it is distinct from the route-definition class router\Router.
In a runtime main(), with a configured controller:
$event = new \router\events\EDynamicRoute();
$event->addRoute(new \router\Router('/health', 'index', $controller));
$this->eventDispatcher->dispatch($event);The bootstrap registers its route.dynamic.add listener before package startup. Prefer ordinary RuntimeRouterAPI registration for static routes; dynamic events are useful for cooperating packages. Do not assume alias or service flags change matching: they are metadata, not URL substitution or authentication policies.
AWT Framework Wiki · Home · Installation Guide · Developer Guide · Framework Internals
Philosophy · Architecture · Known discrepancies · Verification
Installation Guide
Developer Guide
- Learning sequence
- First package
- Package structure
- Lifecycle
- Runtimes
- Events and objects
- Routing and controllers
- Views and resources
- Database and models
- Storage and caching
- Configuration and CLI
- Responses and errors
- Extension points
Framework Internals
- Architecture
- Bootstrap
- Packages
- Runtime
- Events and context
- Objects
- HTTP routing and controllers
- Rendering
- Blade integration
- Database
- Models
- Storage and caching
- Settings
- CLI
- Identity and sessions
- Responses
- Errors
- Complete source inventory
Documentation notes