Skip to content

Instantly share code, notes, and snippets.

@surferxo3
Last active July 26, 2020 11:44
Show Gist options
  • Save surferxo3/b158e085eca52279d6e855d59b40d381 to your computer and use it in GitHub Desktop.
Save surferxo3/b158e085eca52279d6e855d59b40d381 to your computer and use it in GitHub Desktop.
Do some work Before and After the Slim route is executed. Demonstrates the use of Middleware in Slim instead of Hooks.
<?php
/*#############################
* Developer: Mohammad Sharaf Ali
* Designation: Web Developer
* Version: 1.0
*/#############################
use \Psr\Http\Message\ServerRequestInterface as Request;
use \Psr\Http\Message\ResponseInterface as Response;
use \Slim\App as Slim;
require 'vendor/autoload.php';
$config['determineRouteBeforeAppMiddleware'] = true;
$app = new Slim(['settings' => $config]);
$mw = (function (Request $request, Response $response, callable $next) {
// do some work before route invoked
$response = $response->withStatus(200)->write(' before ');
$response = $next($request, $response);
// do some work after route executed
$response = $response->withStatus(200)->write(' after ');
// finally serve data to client
$body = $response->getBody()->__toString();
$response = $response->withJson(array('data' => $body));
return $response;
});
$mw1 = (function (Request $request, Response $response, callable $next) {
$response = $next($request, $response);
$response = $response->withStatus(200)->write(' seq1 ');
return $response;
});
$mw2 = (function (Request $request, Response $response, callable $next) {
$name = $request->getAttribute('route')->getArgument('name');
$response = $next($request, $response);
$response->withStatus(200)->write(' seq2 with name ' . $name);
return $response;
});
$app->add($mw);
$app->get('/hello/{name}', function (Request $request, Response $response) {
$name = $request->getAttribute('name');
$response->getBody()->write(" Hello, $name ");
return $response;
})->add($mw1)->add($mw2);
$app->run();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment