Is it possible to setup a route that calls another routes handler when hit?
Im setting up a vuejs system and instead of using the routes like /api/user/profile
$app->get("/api/user/profile",Controllers\User\ProfileController::class);
I would like to leverage the “name” part on the routes ie:
// Normal api routes.
$app->get("/api/user/profile",Controllers\User\ProfileController::class);
// Then a "special" route that gets the route name as a param and invokes the route by that name.
$app->get("/api/@{routeName}", function (Request $request, ResponseInterface $response) use ($app) {
$name = $request->getAttribute('routeName');
try {
$route = $app->getRouteCollector()->getRouteParser()->urlFor($name);
} catch (\Throwable $exception){
throw new HttpNotFoundException($request,"Route named '{$name}' not found");
}
The above gets me the url for the route and i could probably just do a redirect on that. But i was wondering if there’s a way to actually call / invoke that found routes handler without a redirect?
Sort of like a return $app->getRouteCollector()-getRouteByName($name)->handle($request,$response);
possible solution if the above is not possible:
As a fallback i’ll probably just go with a redirect if this isn’t possible.
Something like:
$route = $app->getRouteCollector()->getRouteParser()->urlFor($name,$request->getQueryParams(),$request->getQueryParams());
The usage for this would be:
//Routes.php
$module->group("/test", function (RouteCollectorProxy $group) {
$group->get("[/{id}]",HomeController::class)->setName("testing_home");
});
$app->get("/api/@{routeName}", function (Request $request, ResponseInterface $response) use ($app) {
$name = $request->getAttribute('routeName');
try {
$route = $app->getRouteCollector()->getRouteParser()->urlFor($name,$request->getQueryParams(),$request->getQueryParams());
// Todo: implement redirect
} catch (\Throwable $exception){
throw new HttpNotFoundException($request,"Route named '{$name}' not found");
}
and in vuejs
api("/api/@testing_home?id=7&testing=abc"
Which outputs the url urlFor($name,$request->getQueryParams(),$request->getQueryParams())
/api/test/3?id=3&test=abc
i could look at prefixing the params with a ?param_id=3&test=abc but i think its less intuitive than just duplicating the query string and the route params. (unless theres a way to get a list of route params used for a route when a route name is given? In which case i would pass just the params to the $data part of urlFor and remove them from the getQueryString() array)