-
Notifications
You must be signed in to change notification settings - Fork 0
ch04_middleware
Daniel Samson edited this page Jan 18, 2024
·
12 revisions
You may need inject features that control your application. TeensyPHP provides the '''middleware' method, to execute callables in order:
middleware(callable ...$method)
Let's say you want to create an API that requires Authorization header. We first need to create a middleware function that returns a callable.
// authorization.php
function authorization(): callable {
return function() {
if (empty(request_header('Authorization')) {
render(403, json_out([]));
stop(); // prevent the pipeline from continuing
}
// TODO: decode the header
// header("Authorization: Bearer " . $token);
};
}
Now we reuse the authorisation check for our routes with the middleware function
route(method(GET), url_path("/"), middleware(authorization, function() {
render(200, json_out(["hello" => "world"]));
}));