PHP code example of dmt-software / http-client-middleware

1. Go to this page and download the library: Download dmt-software/http-client-middleware library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

dmt-software / http-client-middleware example snippets


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
}

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);
    }
}

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);