Search code examples
phpcakephp

How can I get a list of all CakePHP routes?


I'm trying to retrieve a list of all the routes contained in app/Config/routes.php and show them on an admin page. I'm able to retrieve a list of controllers using $controllers = App::objects('controller'); and I was wondering if it's possible to do the same for routes.

I've tried using substrings as per the code below but problems that come to mind are commented out routes, white spaces and variations in routes, e.g. links to external resources. I'm now considering using php's tokenizer but I'd like to know if there is a simple and elegant solution built into CakePHP.

$source = file_get_contents(APP . 'Config/routes.php');

$startPos = stripos($source, 'Router::connect(');

$routes = array();

while ($startPos !== false) {

    $endPos = stripos($source, ';', $startPos + 15);

    if($endPos !== false) {

        $route = substr($source, $startPos, $endPos - $startPos);

        $urlStart = stripos($route, "'");
        if($urlStart !== false) {
            $urlEnd = stripos($route, "'", $urlStart + 1);
            $url = substr($route, $urlStart + 1, $urlEnd - $urlStart - 1);
            $routes[] = array('route'=>$route, 'url'=>$url);

        }

        $startPos = stripos($source, 'Router::connect(', $endPos + 1);
    }
}

Solution

  • Thanks to @ndm for the answer, for anyone trying to retrieve a list of routes parsed by CakePHP's Router (i.e. inside app/Config/routes.php) and also those used for any plugins, use Router::$routes. The output can be a CakeRoute object, RedirectRoute object or a PluginShortRoute object depending on your application.

    $routes = Router::$routes;
    echo('<pre>'); // Readable output
    var_dump($routes);
    echo('</pre>');
    

    For example, the route for Router::connect('/', array('controller' => 'pages', 'action' => 'display', 'home')); shows:

    object(CakeRoute)#16 (7)
    {
      ["keys"] => array(0) {}
      ["options"] => array(0) {}
      ["defaults"] => array(4)
      {
        ["controller"] => string(5) "pages"
        ["action"] => string(7) "display"
        [0] => string(4) "home"
        ["plugin"] => NULL
      }
      ["template"] => string(1) "/"
    }