$app->add(function ($request, $response, $next) { $method = $request->getMethod(); $uri = $request->getUri()->getPath(); $queryParams = $request->getQueryParams(); $response = $next($request, $response); $status = $response->getStatusCode(); $logMessage = "[$method] $uri"; if (!empty($queryParams)) { $logMessage .= " " . json_encode($queryParams); } $logMessage .= " -> $status"; // code to write $logMessage to a log file or database goes here return $response; });
$app->add(function ($request, $response, $next) { $loggedInUserId = // code to get the ID of the currently logged in user if (empty($loggedInUserId)) { // user is not logged in, so redirect to login page $response = $response->withRedirect('/login'); return $response; } // user is logged in, so pass control to the next middleware function $response = $next($request, $response); return $response; });In this example, the hook checks whether `$loggedInUserId` is empty, which indicates that the user is not logged in. If the user is not logged in, the function sets a redirect response and returns it, which prevents the next middleware function from running. If the user is logged in, the function passes control to the next middleware function, which in turn passes control to the route handler. Package library: Slim/Slim