10

In Symfony2, do you know how to find a route from a url in controller? I have this example:

$params = $router->match('/blog/my-blog-post');
// array('slug' => 'my-blog-post', '_controller' => 'AcmeBlogBundle:Blog:show')

$uri = $router->generate('blog_show', array('slug' => 'my-blog-post'));
// /blog/my-blog-post

I would like find blog_show when i have /blog/my-blog-post

Thank you

3 Answers 3

16

I don't know what you have in that $router, but with the router service, I get this here:

$this->get('router')->match('/')

array
  '_controller' => string 'Namespace\Foo\MyController::indexAction'
  '_route' => string 'home'

If you want the route name of the current page by the way you can just read it from the request object: $request->attributes->get('_route').

1
  • $router: it's symfony doc example. I their example they don't show '_route'. I will use it, thank you ! ;)
    – bux
    Nov 22, 2011 at 16:10
1

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).

See more in https://stackoverflow.com/a/16506062/100675

1

you can get the same error if using absolute paths this is what I did when needed to match the referrer

$ref = str_replace("app_dev.php/", "", parse_url($request->headers->get('referer'),PHP_URL_PATH ));
$route = $this->container->get('router')->match($ref)['_route'];
1
  • Nice one but it does not work if you're using other environments than "dev" and "prod", which may be the case for some developers.
    – Alex Rock
    Feb 8, 2014 at 18:21

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.