phpslimpsr-7

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: '/'
require_once('pages/main.php');

// Example page: '/hello'
require_once('pages/hello.php');

// Example page: '/hello/world'
require_once('pages/hello/world.php');

// Contact page: '/contact'
require_once('pages/contact.php');

Each file is a separate page that looks like this

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

    // Some code

})->setName('index');

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.

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

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


Solution

  • 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