Closed pinwhell closed 7 months ago
I understand the concept, but that wasn't quite what I was asking about. I was actually wondering if this library might incorporate middlewares in future updates.
I don't think that's the scope of router itself, rather how you use it. You can, for example map just strings that point to specific classes etc, or you can return usual callables.
What you could do to achieve middleware behavior, instead of mapping single callable, mapping an array of callables that's return value determine if chain should be stopped.
Here is very crude pseudocode to visualize what I mean (note: probably broken pseudocode):
function mw1(Request $i, Response $o) : bool {
if(!validAuth($i->headers->get("Authorization") ?? "")) {
$o->setStatusCode(401);
$o->setContent(json_encode(["error" => "unauthorized"]));
return false;
}
return true;
}
function mw2(Request $i, Response $o) : bool {
$o->headers->set("some-cors-headers", "yes, you can");
if($i->request->isMethod("OPTIONS")) {
$o->setStatusCode(200);
return false;
}
}
function actualHandler(Request $i, Response $o) : void {
$o->setStatusCode(200);
$o->setContent(json_eoncode("error"=>false, "result" => "hello world!"));
}
$router = new AltoRouter();
$router->map( 'GET', '/', [mw1(...), mw2(...), actualHandler(...)], 'home' );
// ...
$result = $router->match();
if($result === false) {
$result = ["target"=>someError404Handle(...)];
}
$request = Request::createFromGlobals(); // symfony http foundation request / response objects
$response = new Response();
for($result["target"] AS $callback) {
if(!is_callable($callback))
throw new LogicException("route must be an array of callables, non callable found");
if(call_user_func_array($callback) === false)
break;
}
$response->prepare($request)->send();
All altorouter does is matching request and giving you back what you gave it, and anything else is up to you.
i see, make sense.
Middle ware is a piece of software that acts as a bridge or connector between different applications or systems. Think of middleware as a mediator or a translator that helps different software components communicate with each other. It sits between two or more systems and facilitates communication, data exchange, or interaction between them.