Skip to content
Belikhun edited this page Sep 15, 2026 · 2 revisions

🗺️ Router

Routes map a path and an HTTP method to a handler. Route files live in routes/ and are loaded from CONFIG::$ROUTES_ROOT; a module can load more with $this -> routes($directory).

Defining routes

use Blink\Http\Router;

Router::GET("/ping", fn () => "pong");

Router::GET("/user/{id}", function (int $id) {
	return User::getByID($id, Model::MUST_EXIST);
});

Router::POST("/user/{id}/rename", [ Users::class, "rename" ]);
Router::DELETE("/user/{id}", "App\\Controller\\Users::delete");
Router::match([ "GET", "POST" ], "/form", [ Forms::class, "handle" ]);
Router::ANY("/webhook", [ Webhooks::class, "receive" ]);

Available: GET, POST, PATCH, DELETE, ANY, and match($methods, ...). Each takes an optional priority as its last argument; when two routes match the same path, the higher priority wins, and among equals the more specific pattern does.

Controllers with attributes

use Blink\Http\Router\Attribute\HttpGet;
use Blink\Http\Router\Attribute\HttpDelete;
use Blink\Http\Router\Attribute\Route;
use Blink\Http\Router\Attribute\RoutePriority;
use Blink\Http\Router\Attribute\Middleware;
use Blink\Http\Router\Attribute\WithoutMiddleware;

class Users {
	#[HttpGet]
	#[Route("/user/{id}")]
	#[Route("/users/{id}")]
	public static function show(int $id) { ... }

	#[HttpDelete]
	#[Route("/user/{id}")]
	#[RoutePriority(10)]
	#[Middleware("audit")]
	#[WithoutMiddleware("cors")]
	public static function delete(int $id) { ... }
}

Router::useController(Users::class);

#[HttpGet], #[HttpHead], #[HttpPost], #[HttpPut], #[HttpPatch], #[HttpDelete] and #[HttpMethod("GET", "POST")] set the verbs. A method may carry several #[Route] attributes.

Path parameters

{name} captures one segment. Numeric segments arrive as int or float; everything else as a string. * matches any one segment without capturing, and ** at the end matches the rest of the path.

Router::GET("/files/**", [ Files::class, "serve" ]);

Handlers receive parameters by name, in any order, alongside anything Essence can inject:

Router::GET("/org/{org}/user/{id}", function (int $id, Request $request, string $org, Mailer $mailer) {});

The request

use Blink\Http\Request;

Router::POST("/search", function (Request $request) {
	$term = $request -> param("q", TYPE_TEXT, default: "");
	$page = $request -> requiredParam("page", TYPE_INT);
	$token = $request -> header("Authorization");
	$session = $request -> cookie("Session");
	$upload = $request -> file("attachment");
	$body = $request -> json(assoc: true);

	if ($request -> accept("application/json"))
		return array( "term" => $term );

	return view("search", array( "term" => $term ));
});

param() reads form data first, then the query string, and cleans the value to the given type. requiredParam() throws MissingParam when it is absent. Types: TYPE_INT, TYPE_FLOAT, TYPE_TEXT (tags stripped), TYPE_RAW, TYPE_BOOL, TYPE_EMAIL, TYPE_USERNAME, TYPE_PHONE, TYPE_JSON, TYPE_JSON_ASSOC.

The request also exposes method, path, args (the captured parameters), route and headers.

Responses

What a handler returns decides the response:

Returned Sent as
string, number, bool The body, as text
array or object JSON, through JsonResponse
a Response As is
a Closure Called, and its return value handled as above
null An empty body

Response classes under Blink\Http\Response:

Class For
Response A body with headers, cookies and a status
JsonResponse An array or object as JSON
APIResponse Blink's API envelope: code, description, data, runtime
FileResponse A file's contents, inline or as a download
PartedFileResponse A byte range of a file, for media streaming
RedirectResponse A redirect
use Blink\Http\Response\Response;
use Blink\Http\Cookie;

return (new Response("Hello"))
	-> status(201)
	-> header("X-Request", $id)
	-> headers(array( "Vary" => "Accept" ), overwrite: false)
	-> cookie((new Cookie("theme", "dark")) -> maxAge(86400) -> path("/") -> httpOnly())
	-> expire(3600);

view($template, $context) renders a template into a Response; template() echoes it.

Middleware

The router runs three Ether stages: route before matching, request after a match and before the handler, response after the handler. Blink's CoreModule installs auth (session and Authorization header), setupEnv (Content-Language, Set-Timezone) and cors.

Router::GET("/status", fn () => "ok")
	-> middleware("api", RateLimit::class)
	-> withoutMiddleware("auth");

See Ether for writing middleware.

Errors

A RouteNotFound becomes a 404 with the error page. Any other throwable becomes a 500, is stored as a report under DATA_ROOT/errors, and is answered with the page or, when the client asked for application/json first, the API envelope. Either way the Report-ID header names the report and /error/{id} shows it again later.

RouteInvalidResponse is raised when a handler returns something the table above cannot send.

Listing

php core/blink route:list
php core/blink route:list --method=POST --path=/api

Clone this wiki locally