woody / http-server-middleware
dev-master
2019-01-30 18:18 UTC
Requires
- php: ^7.1
- psr/http-server-middleware: ^1.0
- woody/http-message: dev-master
Requires (Dev)
This package is auto-updated.
Last update: 2024-10-29 05:22:50 UTC
README
Implements PSR-15 PHP Standard.
Presentation
A middleware component is an individual component participating, often together with other middleware components, in the processing of an incoming request and the creation of a resulting response, as defined by PSR-7.
Middleware are called, one by one, to handle the server request. The first one to create a response will return it to previous middleware. You can transmit object between middleware using attribute attached to the request.
Implementation
Middleware
namespace App; use Psr\Http\Message\ResponseInterface; use Psr\Http\Message\ServerRequestInterface; use Psr\Http\Server\RequestHandlerInterface; use Woody\Http\Message\Response; use Woody\Http\Server\Middleware\MiddlewareInterface; class MyAppMiddleware implements MiddlewareInterface { public function isEnabled(bool $debug): bool { return true; } public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface { if ($request->getUri()->getPath() == '/test') { $data = 'Text 1'; } else { $data = 'Text 2'; } return new Response(200, ['Content-Type' => 'application/json'], json_encode($data)); } }
Middleware declaration
Note: this sample requires http-interop/response-sender
,
available here.
include 'vendor/autoload.php'; use Woody\Http\Server\Middleware\Dispatcher; use Woody\Http\Message\ServerRequest; $request = ServerRequest::fromGlobals(); $dispatcher = new Dispatcher(); $dispatcher->pipe(new LogMiddleware()); $dispatcher->pipe(new ExceptionMiddleware()); $dispatcher->pipe(new SecurityMiddleware()); $dispatcher->pipe(new MyAppMiddleware()); $response = $dispatcher->handle($request); Http\Response\send($response);
Callback declaration
The dispatcher
can also accept callback functions.
include 'vendor/autoload.php'; use Woody\Http\Message\Response; use Woody\Http\Server\Middleware\Dispatcher; use Woody\Http\Message\ServerRequest; $request = ServerRequest::fromGlobals(); $dispatcher = new Dispatcher(); $dispatcher->pipe(new LogMiddleware()); $dispatcher->pipe(function(ServerRequest $request, Dispatcher $dispatcher) { return new Response(200, ['Content-Type' => 'application/json'], json_encode(['user_id' => 42])); }); $response = $dispatcher->handle($request); Http\Response\send($response);