How to access all routes from Slim 3 php framework?
A quick search of the Router class in GitHub project for Slim shows a public method getRoutes()
, which returns the $this->routes[]
array of route objects. From the route object you can get the route pattern using the getPattern()
method:
$routes = $app->getContainer()->router->getRoutes();
// And then iterate over $routes
foreach ($routes as $route) {
echo $route->getPattern(), "<br>";
}
Edit: Added example
Yes. You can name your routes in Slim. This is done in a very simple manner:
$app->get('/hello', function($request, $response) {
// Processing request...
})->setName('helloPage'); // setting unique name for route
Now you can get URL by name like this:
$url = $app->getContainer()->get('router')->pathFor('helloPage');
echo $url; // Outputs '/hello'
You can name routes with placeholders too:
// Let's define route with placeholder
$app->get('/user-profile/{userId:[0-9]+}', function($request, $response) {
// Processing request...
})->setName('userProfilePage');
// Now get the url. Note that we're passing an array with placeholder and its value to `pathFor`
$url = $app->getContainer()->get('router')->pathFor('helloPage', ['userId': 123]);
echo $url; // Outputs '/user-profile/123'
This is sure the way to go, because if you reference routes by names in your templates, then if you need to change a URL, you need to do it only in route defenition. I find this particuarly cool.