Slim: Get all registered routes

Created on 20 Aug 2015  路  4Comments  路  Source: slimphp/Slim

Is it possible somehow to get all the registered routes, their HTTP methods, controllers and functions into an array?

I want to replicate "$ php artisan routes" from Laravel in a cli app so would be nice with this list.

Most helpful comment

For the next poor soul landing here and getting the advice to use the deeply nested -thus unreadable- routes object:

        $routes = array_reduce($this->app->getContainer()->get('router')->getRoutes(), function ($target, $route) {
            $target[$route->getPattern()] = [
                'methods' => json_encode($route->getMethods()),
                'callable' => $route->getCallable(),
                'middlewares' => json_encode($route->getMiddleware()),
                'pattern' => $route->getPattern(),
            ];
            return $target;
        }, []);
        die(print_r($routes, true));

All 4 comments

Zyles, no.

In v3, the callables are only resolved once a route has been chosen to be dispatched.

However you can all of the Route objects through the router.

$app->getContainer()->get('router')->getRoutes();

You can do this using the code above.

For the next poor soul landing here and getting the advice to use the deeply nested -thus unreadable- routes object:

        $routes = array_reduce($this->app->getContainer()->get('router')->getRoutes(), function ($target, $route) {
            $target[$route->getPattern()] = [
                'methods' => json_encode($route->getMethods()),
                'callable' => $route->getCallable(),
                'middlewares' => json_encode($route->getMiddleware()),
                'pattern' => $route->getPattern(),
            ];
            return $target;
        }, []);
        die(print_r($routes, true));

better printout with path and methods

$routes = $app->getContainer()->router->getRoutes();
$list=array();
foreach ($routes as $route) {
    $list[]= $route->getPattern() .' '. json_encode($route->getMethods());
  }
print_r($list);
Was this page helpful?
0 / 5 - 0 ratings

Related issues

l0gicgate picture l0gicgate  路  28Comments

Bilge picture Bilge  路  28Comments

feryardiant picture feryardiant  路  20Comments

l0gicgate picture l0gicgate  路  27Comments

boosis picture boosis  路  25Comments