Slim3 - Route Regexp for UUID


#1

Hello all,
I’m switching over to using UUIDs instead of integers for all of my identifiers which brings many benefits. However, I’m still trying to work through all the possible snags, one of which is trying to use them in slim routing.

When using an auto generated integer, I could use routes like:

$app->get('/users/{id:[0-9]+}', function ($request, $response, $args) {
    // Find user identified by $args['id']
});

However, if using a UUID (example: 8a939c61-5705-421d-a7a1-506cb4b4a773) then I’m trying and failing to use a more complex regular expression and failing with:

$app->get('/users/{id:^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89AB][0-9a-f]{3}-[0-9a-f]{12}$/', function (\Slim\Http\Request $request, Slim\Http\Response $response, $args) {
    // Find user identified by $args['id']
});

Can someone show me how to use more complex regexps with Slim routing for recognizing UUIDs?


#2

Hi!

Take a look at the ramsey/uuid VALID_PATTERN. This regex pattern should be battle tested. :slight_smile:

^[0-9A-Fa-f]{8}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{12}$

#3

Hey that looks awesome. However, I am trying to ask how to perform these complex regexpressions in the routes, not get a regexp that matches a UUID (although that does look useful).

E.g. can you give me a tweaked version of:

$app->get('/users/{id:^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89AB][0-9a-f]{3}-[0-9a-f]{12}$/', function (\Slim\Http\Request $request, Slim\Http\Response $response, $args) {
    // Find user identified by $args['id']
});

… that will actually work with slim routes (its not the regular expression itself but how do i place it in the route?) I have tested that the regular expression itself works using an online tool.


#4

These two rules work for me.

$app->get('/users/{id:[0-9A-Fa-f]{8}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{12}}', function (Request $request, Response $response, $args) {
    $response->write("UUID: " . $args['id']);
    return $response;
});
$app->get('/users/{id:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89AB][0-9a-f]{3}-[0-9a-f]{12}}', function (Request $request, Response $response, $args) {
    $response->write("UUID: " . $args['id']);
    return $response;
});

#5

Awesome thanks, worked for me too :slight_smile: