Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Symfony2 Get route name from URL

Tags:

symfony

ok you can get current route name with app.request.attributes.get('_route') but it's not possible to get from an url ?

Something like app.request.attributes.get('/about') ?

like image 902
altore Avatar asked Mar 27 '13 07:03

altore


People also ask

Where are routes defined in Symfony?

Creating Routes in YAML, XML or PHP Files Instead of defining routes in the controller classes, you can define them in a separate YAML, XML or PHP file.

What is Symfony annotation?

As you might know, Symfony2 uses annotations for Doctrine mapping information and validation configuration. Of course, it is entirely optional, and the same can be done with XML, YAML, or even PHP. But using annotations is convenient and allows you to define everything in the same file.

How does Symfony routing work?

Symfony provides a Routing component which allows us, for a HTTP request/URL, to execute a specific function (also known as "Controller"). Note: Controllers must be a callable, for example: an anonymous function: $controller = function (Request $request) { return new Response() }; .


2 Answers

You can use the Router class/service for this:

public function indexAction()
{
    $router = $this->get('router');
    $route = $router->match('/foo')['_route'];
}

More information in the documentation

like image 111
Wouter J Avatar answered Sep 22 '22 22:09

Wouter J


I recently discovered that the match() method uses the HTTP METHOD of the current request in order to match the request. So if you are doing a PUT request for example, it will try to match the URL you have given with a PUT method, resulting in a MethodNotAllowedException exception (for example, getting the referer).

To avoid this I'm using this workaround:

// set context with GET method of the previous ajax call
$context = $this->get('router')->getContext();
$currentMethod = $context->getMethod();
$context->setMethod('GET');

// match route
$routeParams = $this->get('router')->match($routePath);

// set back original http method
$context->setMethod($currentMethod);

However it may not be true that it's always a GET request. It could be a POST request in your case.

I've sent this problem to the Symfony community. Let's see what they propose.

like image 23
fesja Avatar answered Sep 21 '22 22:09

fesja