How can I get a list of all CakePHP routes?

I am trying to get a list of all routes contained in app / Config / routes.php and show them in the admin page. I can get a list of controllers with $controllers = App::objects('controller');

and I was wondering if it is possible to do this for routes.

I tried to use substrings as per the code below, but the problems that come to mind have commented out routes, spaces and route options for example. links to external resources. I am currently considering using the phken tokenizer, but I would 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);
    }
}

      

+3


source to share


1 answer


Thanks @ndm for the answer, for anyone trying to get a list of routes parsed by CakePHP Router (i.e. inside app / Config / routes.php) as well as those used for any plugins use Router::$routes

. The result can be a CakeRoute object , a 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) "/"
}

      

+4


source







All Articles