简体   繁体   English

检查Symfony 4中是否存在路由

[英]Check if route exists in Symfony 4

How can I test whether a given route exists in Symfony 4 by using the route name. 如何使用路由名称测试Symfony 4中是否存在给定路由。

routes.yaml routes.yaml

home:
  path: /
  controller: App\Controller\Home::index
  methods: [GET]

login:
  path: /login
  controller: App\Controller\Login::index
  methods: [GET]

Controller (making up an exists() method here) 控制器 (在此处构成一个exists()方法)

$routes->exists('home'); // true
$routes->exists('login'); // true
$routes->exists('foo'); // false

From the Symfony 4 Documentation ... Symfony 4文档中 ...

Check if a Route Exists 检查路线是否存在

In highly dynamic applications, it may be necessary to check whether a route exists before using it to generate a URL. 在高度动态的应用程序中,可能有必要在使用路由生成URL之前检查路由是否存在。 In those cases, don't use the getRouteCollection() method because that regenerates the routing cache and slows down the application. 在这种情况下,请勿使用getRouteCollection()方法,因为这会重新生成路由缓存并减慢应用程序的速度。

Instead, try to generate the URL and catch the RouteNotFoundException thrown when the route doesn't exist: 相反,尝试生成URL并捕获不存在路由时引发的RouteNotFoundException:

use Symfony\Component\Routing\Exception\RouteNotFoundException;

// ...

try {
    $url = $generator->generate($dynamicRouteName, $parameters);
} catch (RouteNotFoundException $e) {
    // the route is not defined...
}

You can put that code inside a function and return whatever you need. 您可以将该代码放入函数中,然后返回所需的任何内容。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM