Slim Routing

Table of contents

Loading...

Introduction

The interaction between the browser and the application occurs via URLs. When a user visits a website or makes an HTTP request to a specific URL, the routing system directs that request to the appropriate code or action.
In essence, routing is the process of associating URLs with specific actions, allowing the execution of particular logic and the return of a response.

Defining routes

This mapping is done within the config/routes.php file. The following is an example for the login page action.

// Define which action should be invoked when the URL is /login
$app->get('/login', LoginPageAction::class);
// The `->get` function corresponds to the HTTP method used to access the URL.

The following functions are available for different HTTP methods:

In the login example, there are two separate actions associated with the same URL but different HTTP methods.

File: config/routes.php

use Slim\App;
use App\Application\Action\Authentication\Page\LoginPageAction;
use App\Application\Action\Authentication\Ajax\LoginSubmitAction;

return function (App $app) {
    // Define route that should display the login page and give it a name
    $app->get('/login', LoginPageAction::class)->setName('login-page');
    // Submit login form
    $app->post('/login', LoginSubmitAction::class)->setName('login-submit');
}

Named placeholders

URLs can also have variable parts. For example, if we want to define a route to read specific clients based on their id, a named placeholder can be used for the id.

$app->get('/clients/{id}', ClientReadPageAction::class);

The label id can later be accessed via the $args array that is passed into the Action as the third parameter of the __invoke method.

The format of the placeholder can be specified as follows {label:regexPattern}. For example:

Route groups

URLs that share the same prefix can be grouped together.

For instance, all URLs that start with /client can be grouped together.

$app->group('/clients', function (RouteCollectorProxy $group) {
    $group->get('/{client_id:[0-9]+}', ClientReadPageAction::class)->setName('client-read-page');
    $group->get('', ClientFetchListAction::class)->setName('client-list');
    $group->post('', ClientCreateAction::class)->setName('client-create-submit');
    $group->put('/{client_id:[0-9]+}', ClientUpdateAction::class)->setName('client-update-submit');
    $group->delete('/{client_id:[0-9]+}', ClientDeleteAction::class)->setName('client-delete-submit');
});

More on routes in the Slim 4 documentation.

^