The problem: routing /blogs, not just /blogs/ in Silex
Route mounting in the Silex PHP framework allows conveniently grouping controllers per feature in separate files, then using mounting them on some prefix path like $app->mount('/blogs')
. This will prepend the prefix "/blogs" to the paths defined in the the feature controller, effectively delegating to it all the /blogs/*
routes. However, as the Silex documentation claims:
When mounting a route collection under /blog, it is not possible to define a route for the /blog URL. The shortest possible URL is /blog/.
This means handling the route mount point has to be done by a route outside the mounted feature, which makes it slightly less clean, as you have to do something like:
<?php$blog = require_once __DIR__ . '/controllers-blog.php';// This will handle /blogs/ and below, but not /blogs$app->mount('/blogs', $blog);// So we have to use a non-mounted route from a sub-request to avoid a redirect().$app->get('/blogs', function () use($app) { // forward to /blogs/ $subRequest = Request::create('/blogs/' , 'GET'); return $app->handle($subRequest , HttpKernelInterface::SUB_REQUEST);}?>
But is there really no workaround for this limitation ? Sure there is!