Search code examples
phpsymfonyroutesframeworkssymfony4

Symfony 4 .{_format} not working


so I've got this route

 /**
 * @Route("/user/{id}/diary.{_format}",
 *     defaults={"_format": "json"},
 *     requirements={
 *        "id": "\d+",
 *        "_format": "csv|json"
 *     }
 * )
 */
public function showRaw(User $user, Request $request)
{

}

So when I acccess /user/1/diary it works with whatever I write in the function but when I try to access /user/1/diary.json or /user/1/diary.csv I get an 404 error, so I guess the route parameters are not matching properly.

I would like to, depending on what the format is, return a diferent response but until now I can't get the format.

Thanks in advance for your help.


Solution

  • I assume you are using PHP's built-in development server without an explicit routing script:

    [saizferri:public]$  php -S localhost:5000
    

    or:

    [saizferri:symfony_project]$  php -S localhost:5000 -t public/
    

    When run like this, PHP processes each request by looking in the current directory (or root given with -t) for the requested resource. If it isn't found and PHP thinks it is a file—as it did in the case of /user/1/diary.csv—PHP will return HTTP 404; otherwise, PHP will search for index.php or index.html, and, if either is found, it is served with $_SERVER["PATH_INFO"] set appropriately—this is why you were able to view /user/1/diary. (See the description in the manual.)

    Instead, tell PHP to route all requests through public/index.php:

    php -S localhost:<port> public/index.php