dmt-software / http-client-middleware
HTTP client request handler
Installs: 10 728
Dependents: 3
Suggesters: 0
Security: 0
Stars: 0
Watchers: 3
Forks: 0
Open Issues: 0
Requires
- php: >=8.1
- psr/http-client: ^1.0
- psr/http-factory: ^1.0
- psr/http-message: ^2.0
- psr/simple-cache: ^1.0
Requires (Dev)
- ext-zlib: *
- guzzlehttp/guzzle: ^7.9
- phpunit/phpunit: >=9.5
Suggests
- ext-zlib: Needed to use ZlibInflateMiddleware
README
Unfortunately psr-15, the recommendation how to handle incoming server request, does not cover how to deal with an outgoing request or a client response.
This package solves that problem.
Installation
composer require dmt-software/http-client-middleware
Usage
use DMT\Http\Client\RequestHandler; use Psr\Http\Client\ClientInterface; use Psr\Http\Message\RequestInterface; /** @var ClientInterface $client */ $handler = new RequestHandler($client); $response = $handler->handle($request); if ($response->getStatusCode() === 200) { // process the response }
Middleware
Middleware can be used to process a request before it is sent to the server by the client or to handle the response, for instance to apply authentication, store a login cookie or log the response.
use DMT\Http\Client\MiddlewareInterface; use DMT\Http\Client\RequestHandlerInterface; use Psr\Http\Message\ResponseInterface; use Psr\Http\Message\RequestInterface; /** * Apply basic authentication header to the request */ class BasicAuthMiddleware implements MiddlewareInterface { private string $user = 'user'; private string $pass = '*****'; public function process(RequestInterface $request, RequestHandlerInterface $handler): ResponseInterface { $request = $request->withHeader( 'Authorization', sprintf('Basic %s', base64_encode("$this->user:$this->pass")) ); return $handler->handle($request); } }
To enable middleware simply add these to the request handler.
use DMT\Http\Client\RequestHandler; use Psr\Http\Client\ClientInterface; use Psr\Http\Message\RequestInterface; /** @var ClientInterface $client */ $handler = new RequestHandler( $client, $basicAuthMiddleware, $otherMiddleware, ); $response = $handler->handle($request);