在我看来,最好的方法是使用 Slim 的内部路由器 (Slim\Router) 功能并调度 (Slim\Route::dispatch()) 匹配的路由(意思是:从匹配的路由执行可调用而不需要任何重定向) .有几个选项浮现在脑海中(取决于您的设置):
1。调用命名路由 + 可调用不带任何参数(您的示例)
$app->get('/logout',function () use ($app) {
$app->view->set("logout",true);
// here comes the magic:
// getting the named route
$route = $app->router()->getNamedRoute('login');
// dispatching the matched route
$route->dispatch();
})->name("logout");
这肯定对你有用,但我仍然想展示其他场景......
2。调用命名路由 + 可调用参数
上面的例子会失败......因为现在我们需要将参数传递给可调用对象
// getting the named route
$route = $app->router()->getNamedRoute('another_route');
// calling the function with an argument or array of arguments
call_user_func($route->getCallable(), 'argument');
调度路由(使用 $route->dispatch())将调用所有中间件,但这里我们只是直接调用可调用对象......所以要获得完整的包,我们应该考虑下一个选项......
3。调用任意路由
如果没有命名路由,我们可以通过找到与 http 方法和模式匹配的路由来获得路由。为此,我们使用 Router::getMatchedRoutes($httpMethod, $pattern, $reload) 并将重新加载设置为 TRUE。
// getting the matched route
$matched = $app->router()->getMatchedRoutes('GET','/classes/name', true);
// dispatching the (first) matched route
$matched[0]->dispatch();
在这里您可能想要添加一些检查,例如调度notFound,以防没有匹配的路线。
我希望你明白了 =)