8

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') ?

3 Answers 3

15

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

Sign up to request clarification or add additional context in comments.

2 Comments

I used this but it's not valid. The Route service in Symfony has state of current request. For get the real route you should set context created from request with HTTP method that can be POST, PATCH or PUT or any other.
sidenote: I'm not sure if this example was ever denoted in the documentation, but it no longer is (7.x).
10

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.

1 Comment

You can force HEAD method instead GET. If you check appDevUrlMatcher.php or appProdUrlMatcher.php in your cache files, you will see HEAD method is always allowed for all routes. With this you will no longer need to estimate which method use to match referer.
6

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'];

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.