How do you define and use custom route patterns in Slim Framework?

How do you define and use custom route patterns in Slim Framework?

 

To define and use custom route patterns in Slim Framework with minimal steps:

1. Define Route with Custom Pattern

Use regular expressions to constrain route parameters:

Example

<?php
$app->get('/user/{id:[0-9]+}', function ($request, $response, $args) {
    $userId = $args['id'];  // Only accepts numeric values
    $response->getBody()->write("User ID: $userId");
    return $response;
});
?>
  • {id:[0-9]+} ensures id is numeric.

2. Multiple Patterns in a Route

To define multiple parameters with constraints:

Example

<?php
$app->get('/profile/{id:[0-9]+}/{username:[a-zA-Z]+}', function ($request, $response, $args) {
    $userId = $args['id'];
    $username = $args['username'];
    $response->getBody()->write("User ID: $userId, Username: $username");
    return $response;
});
?>
  • {id:[0-9]+} for numeric id.
  • {username:[a-zA-Z]+} for alphabetic username.

3. Optional Parameters with Patterns

Example

<?php
$app->get('/profile/{id:[0-9]+}[/{username:[a-zA-Z]+}]', function ($request, $response, $args) {
    $userId = $args['id'];
    $username = $args['username'] ?? 'Guest';
    $response->getBody()->write("User ID: $userId, Username: $username");
    return $response;
});
?>

Optional {username} using square brackets.

Related Questions & Topics

Powered and designed by igetvapeaustore.com | © 2024 codestap.com.