Check url before redirect symfony2

我与影子孤独终老i 提交于 2019-12-23 09:05:52

问题


if ($u = $this->generateUrl('_'.$specific.'_thanks'))
  return $this->redirect($u);
else
  return $this->redirect($this->generateUrl('_thanks'));

I wan't to redirect to the _specific_thanks url when it exist. So How to check if a url exist?

When I did that, I had this error:

Route "_specific_thanks" does not exist.


回答1:


I don't think there's a direct way to check if a route exists. But you can look for route existence through the router service.

$router = $this->container->get('router');

You can then get a route collection and call get() for a given route, which returns null if it doesn't exist.

$router->getRouteCollection()->get('_'. $specific. '_thanks');



回答2:


Using getRouteCollection() on runtime is not the correct solution. Executing this method will require the cache to be rebuilt. This means that routing cache will be rebuilt on each request, making your app much slower than needed.

If you want to check whether a route exists or not, use the try ... catch construct:

use Symfony\Component\Routing\Exception\RouteNotFoundException;

try {
    dump($router->generate('some_route'));
} catch (RouteNotFoundException $e) {
    dump('Oh noes, route "some_route" doesn't exists!');
}



回答3:


Try something like this, check the route exists in the array of all routes:

    $router = $this->get('router');

    if (array_key_exists('_'.$specific.'_thanks',$router->getRouteCollection->all())){
        return $this->redirect($this->generateUrl('_'.$specific.'_thanks'))
    } else {
        return $this->redirect($this->generateUrl('_thanks'));
    }



回答4:


Did you check your cast? And are you sure about the route? usually route start with

'WEBSITENAME_'.$specific.'_thanks'



回答5:


Try this:

if ($u == $this->generateUrl('_'.$specific.'_thanks') )


来源:https://stackoverflow.com/questions/14136484/check-url-before-redirect-symfony2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!