Skip to content

Slim3 Routes

Last updated on February 20, 2018

The router component allows you to define routes that are mapped to callback handlers that should receive the request. The Slim Framework’s router is built on top of the nikic/fastroute component, and it is remarkably fast and stable. A router simply parses a URI to determine the request and gives an appropriate response to it.

Simple get request

get('/', function($request, $response) {
      $response->write("Hello world");
      return $response;
});
$app->run();

The Slim Framework provides methods for the most popular HTTP methods.

$app->get() - Which will handles only GET HTTP requests 
$app->post() - Which will handles only POST HTTP requests 
$app->put() - Which will handles only PUT HTTP requests 
$app->patch() - Which will handles only PATCH HTTP requests 
$app->delete() - Which will handles only DELETE HTTP requests 
$app->options() - Which will handles only OPTIONS HTTP requests 
$app->map([‘get’, ‘post’]) // Which will handles specified multiple HTTP requests.  

Dynamic routes

$app->get('/hello/{name}',
   function($request, $response, $args) {
           $name = $args['name'];
           return $response->write("Hello $name");
});

Regex in Routes

$app->get('/user/{id:\d+}', $callable);
$app->get('/hello/{name:[\w]+}', $callable);
$app->get('/hello{a:/{0,1}}{name:[\w]*}', $callable);

Route groups

$app->group('/books', function () use ($app) { $app->get('', function ($req, $res) { // Return list of books }); $app->post('', function ($req, $res) { // Create a new book }); $app->get('/{id:\d+}', function ($req, $res, $args) { // Return a single book }); $app->put('/{id:\d+}', function ($req, $res, $args) { // Update a book }); });

Named routes

// Name the route
$app->get('/hello/{name}', function(...) {...})
->setName('hi');

// build link:
$link = $app->router->urlFor('hi', ['name' => 'Rob']);
creates: /hello/Rob
0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments