Andrei Oniga
Andrei Oniga

Reputation: 8559

How to set up case insensitive routes with Slim framework?

I have the following association between a route and a callback in my application:

$api->slim->post('/:accountId/Phone-Numbers/', function($accountId) use ($api) {
    $api->createPhoneNumber($accountId);
});

What I want to avoid is having the route myhost/a7b81cf/phone-numbers/ return a 404 response because Slim understands the route myhost/a7b81cf/Phone-Numbers/ as being different, due to the usage of uppercase letters. How can I avoid setting up two separate routes that trigger the same callback function?

Upvotes: 5

Views: 1772

Answers (3)

federicojasson
federicojasson

Reputation: 382

This is an old question, but I wanted to provide a clear answer for this problem.

There is a 'routes.case_sensitive' configuration that allows you to do that. I don't know exactly why this is not in the docs (http://docs.slimframework.com/#Application-Settings), but if you look at the framework's source code (specifically, in getDefaultSettings() at Slim.php) you can see that is there.

I just tested it and it works fine.

Summarizing, the solution is to apply the 'routes.case_sensitive' configuration like this:

$configurations = [
    // ... other settings ...
    'routes.case_sensitive' => false
];

$app->config($configurations);

Upvotes: 6

Jeremy Kendall
Jeremy Kendall

Reputation: 2869

You can mimic case-insensitive routing in Slim by registering a hook and modifying the incoming routes to match the case of your defined routes.

In the example, all of your defined routes should be lowercase and strtolower is called on all incoming paths:

$app->hook('slim.before.router', function () use ($app) {
    $app->environment['PATH_INFO'] = strtolower($app->environment['PATH_INFO']);
});

Upvotes: 0

f1ames
f1ames

Reputation: 1734

You could try with route validation/conditions:

$api->slim->post('/:accountId/:phoneNumbers/', function ($accountId) {
    $api->createPhoneNumber($accountId);
})->conditions(array('phoneNumbers' => '(p|P)hone\-(n|N)umbers'));

Or if you want more global change you could override Route->matches method in Route class to be case insensitive but it will affect whole application.

Upvotes: 0

Related Questions