For Slim3, an example is shown showing how to get routing information from middleware, which is actually a combination of the previous answers.
<?php $slimSettings = array('determineRouteBeforeAppMiddleware' => 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) {
In my case, I wanted to add middleware that would allow the user to enter certain routes and redirect to the login page if they were not. I found that the easiest way to do this is to use ->setName() on such routes:
$app->get('/', function (\Slim\Http\Request $request, Slim\Http\Response $response, $args) { return $response->withRedirect('/home'); })->setName('index');
Then, if this route was matched, $routeName in the middleware example would be "index" . Then I determined a list of route arrays that did not require authentication, and checked if the current route was on this list. For example.
if (!in_array($routeName, $publicRoutesArray)) {
Programster
source share