Silex Routing and Trailing Slashes

Silex treats a route like /profile/1 as a different resource to /profile/1/, nothing wrong with that.

However, when using controller providers, root level routes for that controller are mounted with a trailing slash, which leads to potentially undesired behaviour.

For example:

class ProfileControllerProvider implements ControllerProviderInterface  
{
    public function connect(Application $app)
    {
        $controllers = $app['controllers_factory'];

        $controllers->post('/', function () {
            return 'Foo';
        });

        return $controllers;
    }
}

$app->mount('/profile', new ProfileControllerProvider());

In this case POST requests to /profile will 404, as /profile/ is the registered route.

@jrschumacher posted a handy meta-route to handle this, however unless you override the default url matcher, GET requests will continue to be handled in RedirectableUrlMatcher and respond with a redirect.

I wrote a simple controller provider that iterates on @jrschumacher's work, defining the route and overriding the registered url_matcher correctly:

https://github.com/graze/silex-trailing-slash-handler

Here at graze, we're always looking to hire smart people to join our tech team. If you love solving the types of technical challenges we face, send your CV to jobs@graze.com.

comments powered by Disqus