Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
774 views
in Technique[技术] by (71.8m points)

symfony - How to get list of all routes of a controller in Symfony2?

I have a controller which implements all routes/URL(s). I had the idea to offer a generic index over all help-pages.

Is there a way to get all routes defined by a controller (from within a controller) in Symfony2?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

What you can do is use the cmd with (up to SF2.6)

php app/console router:debug

With SF 2.7 the command is

php app/console debug:router

With SF 3.0 the command is

php bin/console debug:router

which shows you all routes.

If you define a prefix per controller (which I recommend) you could for example use

php app/console router:debug | grep "<prefixhere>"

to display all matching routes

To display get all your routes in the controller, with basically the same output I'd use the following within a controller (it is the same approach used in the router:debug command in the symfony component)

/**
 * @Route("/routes", name="routes")
 * @Method("GET")
 * @Template("routes.html.twig")
 *
 * @return array
 */
public function routeAction()
{
    /** @var Router $router */
    $router = $this->get('router');
    $routes = $router->getRouteCollection();

    foreach ($routes as $route) {
        $this->convertController($route);
    }

    return [
        'routes' => $routes
    ];
}


private function convertController(SymfonyComponentRoutingRoute $route)
{
    $nameParser = $this->get('controller_name_converter');
    if ($route->hasDefault('_controller')) {
        try {
            $route->setDefault('_controller', $nameParser->build($route->getDefault('_controller')));
        } catch (InvalidArgumentException $e) {
        }
    }
}

routes.html.twig

<table>
{% for route in routes %}
    <tr>
        <td>{{ route.path }}</td>
        <td>{{ route.methods|length > 0 ? route.methods|join(', ') : 'ANY' }}</td>
        <td>{{ route.defaults._controller }}</td>
    </tr>
{% endfor %}
</table>

Output will be:

/_wdt/{token} ANY web_profiler.controller.profiler:toolbarAction etc.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...