从 symfony 请求获取 prod URI 的最佳方法 - 在开发环境中

Best way to get a prod URI from symfony request - while being in dev environment

我正在我的数据库中存储 url 个 slug,如下所示:/blog/important-article。然后,我的 BlogController 将对 /blog 下资源的任何请求解析为相应的数据库条目。

这工作正常,但在开发环境中我仍然必须使用解决方法,因为开发路径是 /app_dev.php/blog/important-article - 这确实数据库中不存在:

public function blogAction(Request $request)
{
    $slug = $request->getRequestUri(); // matches to regex \/(app_dev.php\/)?blog\/.+
    //...
}

我尝试了两种都有效的解决方法,但我认为它们不是可行的方法:

  1. 在控制器中使用$slug = str_replace ('app_dev.php/', '', $slug);
  2. 在路由配置中捕获实际的 slug (/blog/important-article) 并将其作为参数交给控制器。然后做 $slug = '/blog/'.$slugPart;

是否有获取 prod Uri 的 symfony 方法(即使在开发环境中)?

[编辑:] @gp_sflover 建议的 "possible" 副本具有完全不同的重点。它更多地是关于 getPathInfo() 的 documentation/usage 而不是为什么以及何时使用它。另一方面,我的问题是关于一个特定的用例——其中 getPathInfo() 是人们可能正在寻找的实际解决方案。

您可以使用 pathInfo() 方法:

In your application, you need a way to identify a request; most of the time, this is done via the "path info" of the request, which can be accessed via the getPathInfo() method:

// for a request to http://example.com/blog/index.php/post/hello-world
// the path info is "/post/hello-world"
$request->getPathInfo();

希望对您有所帮助