Vladimir Jovanović Vladimir Jovanović - 1 year ago 91
PHP Question

How to access all routes from Slim 3 php framework?

I am trying to build a dynamic drop-down menu from routes defined in Slim framework and here is my question - is there a way to access all defined static routes from some kind of array?

For instance, if I define my routes like this:

// Index page: '/'

// Example page: '/hello'

// Example page: '/hello/world'

// Contact page: '/contact'

Each file is a separate page that looks like this

// Index page
$app->get('/', function ($request, $response, $args) {

// Some code


I would like to access all of these defined routes from some sort of array and then use that array to make a unordered HTML list in my template files.

<li><a href="/">Index</a></li>
<li><a href="/hello">Hello</a>
<li><a href="/hello/world">World</a></li>
<li><a href="/contact">Contact</a></li>

Whenever I change defined routes, I would like this menu to change with it. Is there a way to achieve this?

Answer Source

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download