Limiting into Middleware • Build say a standard set of responses for generic queries into Middleware • Build an entire CRUD application using Middleware, sure. CC BY-NC 4.0 Justin Yost 7
/** * Participant in processing a server request and response. * * An HTTP middleware component participates in processing an HTTP message: * by acting on the request, generating the response, or forwarding the * request to a subsequent middleware and possibly acting on its response. */ interface MiddlewareInterface { /** * Process an incoming server request. * * Processes an incoming server request in order to produce a response. * If unable to produce the response itself, it may delegate to the provided * request handler to do so. */ public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface; } CC BY-NC 4.0 Justin Yost 9
class LogMiddleware interface MiddlewareInterface { public function __construct(LoggerInterface $logger) { $this->logger = $logger; } public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface { // before request $this->logger->info('Request Body {body}', ['body' => $request->getParsedBody()]); // request handled by rest of the stack of middleware and the application $response = $handler->handle($request); // on returning a response return $response; } } CC BY-NC 4.0 Justin Yost 10
$handler): ResponseInterface { // before request if ($this->notAuthed()) { return $this->throwError(); } // request handled by rest of the stack of middleware and the application $response = $handler->handle($request); // on returning a response return $response; } } CC BY-NC 4.0 Justin Yost 12
$handler): ResponseInterface { // before request // request handled by rest of the stack of middleware and the application $response = $handler->handle($request); // on returning a response $response = $response->withAddedHeader('Access-Control-Allow-Origin', 'https://myawesome.org'); return $response; } } CC BY-NC 4.0 Justin Yost 13
• CakePHP (PSR-15 full support in Cake 4, currently alpha2) • Slim (PSR-15 full support in Slim4, currently alpha) • Roll your own CC BY-NC 4.0 Justin Yost 14
before request // request handled by rest of the stack of middleware and the application $response = $next($request); // after the response has been crafted return $response } CC BY-NC 4.0 Justin Yost 16