phpsymfonyrequesturi

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


I am storing url slugs in my database, like this: /blog/important-article. My BlogController then resolves any requests to a resource below /blog to the corresponding database entry.

This works fine, but in the dev environment I still have to use a workaround as the dev path is /app_dev.php/blog/important-article - which does not exist in the database:

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

I tried two workarounds that both work, but I don't think they are the way to go:

  1. Use $slug = str_replace ('app_dev.php/', '', $slug); in the controller.
  2. Catch the actual slug (/blog/important-article) in the routing configuration and hand it over to the controller as an argument. Then do $slug = '/blog/'.$slugPart;

Is there a symfony way of getting the prod Uri (even while in dev environment)?

[Edit:] the "possible" duplicate suggested by @gp_sflover has a completely different focus. It is more about the documentation/usage of getPathInfo() than about why and when to use it. My question on the other hand is about a specific use case - where getPathInfo() is the actual solution one might be looking for.


Solution

  • You could use the pathInfo() method:

    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();
    

    Hope this help