Hello everyone!

We have been investing plenty of personal time and energy for many years to share our knowledge with you all. However, we now need your help to keep this blog running. All you have to do is just click one of the adverts on the site, otherwise it will sadly be taken down due to hosting etc. costs. Thank you.

Example below will show you how to get the list of all routes in a controller.


Check bundles


Now it is obvious that we have system routers starting with application_frontend and application_backend prefixes.


# app/config/routing.yml

application_frontend:
resource: "@ApplicationFrontendBundle/Controller"
prefix: /
type: annotation

application_backend:
resource: "@ApplicationBackendBundle/Controller"
prefix: /backend
type: annotation

Controllers.yml


services:
application_frontend.controller.profile:
class: Application\FrontendBundle\Controller\ProfileController
arguments:
- @router
- @doctrine_common_inflector

doctrine_common_inflector:
class: Doctrine\Common\Inflector\Inflector

Controller


You can do a bit of cleaning here because I left it a bit messy for this time!


use Doctrine\Common\Inflector\Inflector;
use Symfony\Component\Routing\RouterInterface;
# .......

/**
* @Route("profile", service="application_frontend.controller.profile")
*/
class ProfileController
{
private $router;
private $inflector;

public function __construct(
RouterInterface $router,
Inflector $inflector
) {
$this->router = $router;
$this->inflector = $inflector;
}

/**
* @Method({"GET"})
* @Route("/step_one")
*/
public function stepOneAction()
{
$list = [];
$myRoutes = ['application_frontend', 'application_backend'];
$routeCollection = $this->router->getRouteCollection();

foreach ($routeCollection->all() as $key => $value)
{
$data = $value->getDefaults();

if (isset($data['_controller'])) {
foreach ($myRoutes as $routePrefix) {
if (strstr($data['_controller'], $routePrefix) !== false) {
$routeParts = explode(':', $data['_controller']);
$routeParts2 = explode('.', $routeParts[0]);

$list[] = end($routeParts2). '/' . $this->inflector->tableize(end($routeParts));
}
}
}
}

print_r($list);
exit;
}
}

Result


Array
(
[0] => country/index_action
[1] => country/list_action
[2] => default/index_action
[3] => default/list_action
[4] => profile/step_one_action
[5] => profile/step_two_action
[6] => profile/step_one_process_action
[7] => profile/step_two_process_action
[8] => security/index_action
[9] => security/login_action
[10] => security/logout_action
[11] => api/json_action
[12] => api/xml_action
[13] => api/json_xml_action
[14] => default/index_action
[15] => default/list_action
[16] => default/secret_action
[17] => superadmin/index_action
[18] => superadmin/list_action
[19] => twitter/list_action
[20] => twitter/create_tweet_action
[21] => user/list_action
[22] => user/create_action
)