Reputation: 245
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')
?
Upvotes: 8
Views: 21434
Reputation: 123
I was getting the MethodNotAllowed even with matching methods when using absolute paths I worked around it like this
$ref = str_replace("app_dev.php/", "", parse_url($request->headers->get('referer'),PHP_URL_PATH ));
$route = $this->container->get('router')->match($ref)['_route'];
Upvotes: 6
Reputation: 3313
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.
Upvotes: 10
Reputation: 41954
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
Upvotes: 15