Slim 3 get current route in middleware

后端 未结 5 1966
故里飘歌
故里飘歌 2021-01-04 13:30

I want to get the name of the current I route in a middleware class. Previously (in Slim 2.*) you could fetch the current route like so:

$route = $this->ap

5条回答
  •  青春惊慌失措
    2021-01-04 14:05

    For Slim3, here is an example showing you how to get routing information from within middleware, which is actually a combination of previous answers put together.

     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....
    })
    

    In my case, I wanted to add middleware that would ensure the user was logged in on certain routes, and redirect them to the login page if they weren't. I found the easiest way to do this was to use ->setName() on the routes like so:

    $app->get('/', function (\Slim\Http\Request $request, Slim\Http\Response $response, $args) {
        return $response->withRedirect('/home');
    })->setName('index');
    

    Then if this route was matched, the $routeName in the middleware example will be "index". I then defined my array list of routes that didn't require authentication and checked if the current route was in that list. E.g.

    if (!in_array($routeName, $publicRoutesArray))
    {
        # @TODO - check user logged in and redirect if not.
    }
    

提交回复
热议问题