Mount operation in Silex - additional trailing slash

1.1k Views Asked by At

I have a small backend developed in Silex Framework. I try to make this request work on POST:

http://localhost/feedback/other

but when using mount operation only this request works:

http://localhost/feedback/other/

As you can see I must add an additional trailing slash to the request.

Here is some code that doesn't work as expected:

//index.php
$app->mount("/other", new FeedbackOther());

//FeedbackOther.php
$feedbackOther->get("/", "FeedbackOtherController::index")->bind('other');
$feedbackOther->post("","FeedbackOtherController::store");

If I do something like

//index.php
$app->post('/other', "FeedbackOtherController::store");
$app->mount("/other", new FeedbackOther());

//FeedbackOther.php
$feedbackOther->get("/", "FeedbackOtherController::index")->bind('other');

The POST request works without the additional slash, but in this case I don't see the point in using mount operation.

Also I've tried using .htacces rewrite but the rewrite rule transforms the POST request in GET.

1

There are 1 best solutions below

0
On BEST ANSWER

There is a difference between mounting a collection of routes and simply limiting a route to post. Adding mount means that a collection of routes are being created under specific namespace, in your case that would be /other. Meaning that the default URL for this namespace would be /other/ - trailing slash is required too. That does not apply when you define your routes to specific method, such as post. In short - this is the expected behaviour in both Silex and Symfony as well. There was a heavy discussion about this in github a while ago, so let me copy/paste you the notes Fabien left (the author):

Let me explain the current behavior of mounted routes so that everybody understand the behavior explained by several people in this thread (and this behavior is the same as the one in Symfony, so it applies to Symfony as well).

The simplest URL possible is / (an empty URL does not mean anything and is silently converted by browsers to /, so when you are requesting http://google.com, the actual request is for http://google.com/).

When you mount a route collection under a prefix, Silex/Symfony creates a new "namespace" for those URLs. When you define / in a route collection and then mount it under /foo, the URL to access this route is /foo/. Requesting /foo in this case does not make sense.

So, as of today, it is not possible to define a callback for /foo when mounting a route collection under /foo. I can see the limitation of the current behavior but I can't think of a possible solution that does not feel hackish.

If you're interested in the whole story - this is where the quote is taken.