如何使用 Slim Framework 转发 HTTP 请求


How to forward an HTTP request with Slim Framework

是否可以在 Slim 中转发请求?与JavaEE一样,"forward"的含义是在内部重定向到另一个路由,而不将响应返回给客户端并维护模型。

例如:

$app->get('/logout',function () use ($app) {
   //logout code
   $app->view->set("logout",true);
   $app->forward('login'); //no redirect to client please
})->name("logout");
$app->get('/login',function () use ($app) {
   $app->render('login.html');
})->name("login");

在我看来,最好的方法是使用 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,以防没有匹配的路由。我希望你明白这个想法=)

redirect()方法。但是,它会发送您不想要的302 Temporary Redirect响应。

$app->get("/foo", function () use ($app) {
    $app->redirect("/bar");
});

另一种可能性是pass()它告诉应用程序继续到下一个匹配路由。当调用pass()时,Slim将立即停止处理当前匹配路由并调用下一个匹配路由。

如果未找到后续匹配路由,则会向客户端发送404 Not Found

$app->get('/hello/foo', function () use ($app) {
    echo "You won't see this...";
    $app->pass();
});
$app->get('/hello/:name', function ($name) use ($app) {
    echo "But you will see this!";
});

我认为您必须重定向它们。斯利姆没有前锋。但是,例如,您可以在重定向功能中设置状态代码。当您重定向到路由时,您应该获得所需的功能。

// With route
$app->redirect('login');
// With path and status code
$app->redirect('/foo', 303);

下面是文档中的示例:

<?php
$authenticateForRole = function ( $role = 'member' ) {
    return function () use ( $role ) {
        $user = User::fetchFromDatabaseSomehow();
        if ( $user->belongsToRole($role) === false ) {
            $app = 'Slim'Slim::getInstance();
            $app->flash('error', 'Login required');
            $app->redirect('/login');
        }
    };
};