How to understand the routing middleware of Slim through the source code?

I encountered some problems in the process of reading the Slim source code. After reading the source code, I looked at the official document application and wanted to understand the application process, such as the implementation process of routing middleware in the document. I would like to ask, through the source code analysis of this process, the main confusion is how to bind routing middleware with routing?

<?php
$app = new \Slim\App();

$mw = function ($request, $response, $next) {
    $response->getBody()->write("BEFORE");
    $response = $next($request, $response);
    $response->getBody()->write("AFTER");

    return $response;
};

$app->get("/", function ($request, $response, $args) {
    $response->getBody()->write(" Hello ");

    return $response;
})->add($mw);

$app->run();

output:
BEFORE Hello AFTER

Dec.27,2021
Menu