我想在中间件类中获取当前I路由的名称.以前(在Slim 2.*中)你可以像这样获取当前路线:
$route = $this->app->router->getCurrentRoute();
但是这个功能已经在3.0版的Slim中被删除了.我在以下__invoke
方法中找到了以下代码Slim\App
:
// Get the route info $routeInfo = $request->getAttribute('routeInfo'); /** @var \Slim\Interfaces\RouterInterface $router */ $router = $this->container->get('router'); // If router hasn't been dispatched or the URI changed then dispatch if (null === $routeInfo || ($routeInfo['request'] !== [$request->getMethod(), (string) $request->getUri()])) { $request = $this->dispatchRouterAndPrepareRoute($request, $router); $routeInfo = $request->getAttribute('routeInfo'); }
这表明,当前的路线被存储为属性routeInfo
的Request
.但似乎我的自定义中间件类在设置属性之前被调用(通过该$this->dispatchRouterAndPrepareRoute($request, $router);
方法).因为呼叫$request->getAttribute('routeInfo')
解决了NULL
.
所以我的问题是; 如何从中间件函数/类中获取当前路由(或路由名称)?
或者我应该只复制上面的代码Slim\App
?
对于Slim3,这里有一个示例,向您展示如何从中间件中获取路由信息,这实际上是先前答案放在一起的组合.
true); // This is not necessary for this answer, but very useful if (ENVIRONMENT == "dev") { $slimSettings['displayErrorDetails'] = true; } $slimConfig = array('settings' => $slimSettings); $app = new \Slim\App($slimConfig); $myMiddleware = function ($request, $response, $next) { $route = $request->getAttribute('route'); $routeName = $route->getName(); $groups = $route->getGroups(); $methods = $route->getMethods(); $arguments = $route->getArguments(); print "Route Info: " . print_r($route, true); print "Route Name: " . print_r($routeName, true); print "Route Groups: " . print_r($groups, true); print "Route Methods: " . print_r($methods, true); print "Route Arguments: " . print_r($arguments, true); }; // Define app routes $app->add($myMiddleware); $app->get('/', function (\Slim\Http\Request $request, Slim\Http\Response $response, $args) { # put some code here.... })
就我而言,我想添加中间件以确保用户在某些路由上登录,如果不是,则将其重定向到登录页面.我发现最简单的方法就是->setName()
在路由上使用:
$app->get('/', function (\Slim\Http\Request $request, Slim\Http\Response $response, $args) { return $response->withRedirect('/home'); })->setName('index');
然后,如果此路由匹配,$routeName
则中间件示例中将是"index"
.然后,我定义了不需要身份验证的路由的数组列表,并检查当前路由是否在该列表中.例如
if (!in_array($routeName, $publicRoutesArray)) { # @TODO - check user logged in and redirect if not. }
显然,您可以使用此设置配置Slim以确定进入中间件之前的路由:
$app = new Slim\App([ 'settings' => [ 'determineRouteBeforeAppMiddleware' => true, ] ]);
我不确定它有什么样的影响,但它对我有用:)
$request->getUri()->getPath()
获取当前路线,即使在middleware
.