Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get a list of all CakePHP routes?

Tags:

php

cakephp

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);
    }
}
like image 591
danialk Avatar asked Sep 11 '25 02:09

danialk


2 Answers

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) "/"
}
like image 72
danialk Avatar answered Sep 12 '25 16:09

danialk


You can also use bin/cake routes Documentation

And also use for JSON export :

public function routes() {
    $routes = Router::routes();
    return $this->response->withStringBodyAsJson($routes);
}

If you want to list All Routes, including Controllers auto-generated routes see here list-all-controllers-actions-in-cakephp-3 , Note : you have to edit this script if you use prefix.

like image 24
PetitCitron Avatar answered Sep 12 '25 17:09

PetitCitron