PHP code example of rebelcode / wp-http

1. Go to this page and download the library: Download rebelcode/wp-http 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/ */

    

rebelcode / wp-http example snippets


use RebelCode\WordPress\Http\WpClient;
use RebelCode\WordPress\Http\WpHandler;
use RebelCode\WordPress\Http\HandlerStack;
use RebelCode\WordPress\Http\Middleware;

/*-----------------------------------------------------------------------------
 * Default configuration.
 * - Uses the `WpHandler`
 * - Uses the `HttpErrorsToExceptions` middleware
 * - Uses the `PrepareBody` middleware
 */
 
$client = WpClient::createDefault('https://base-url.com/api', [
    'timeout' => 30,
    'redirection' => 3,
]);

/*-----------------------------------------------------------------------------
 * Custom configuration with middleware:
 * - Create the `WpHandler`
 * - Create a `HandlerStack` with the handler and middleware factories
 * - Create the `WpClient` and pass the stack
 */
 
$wpHandler = new WpHandler([
    'timeout' => 30,
    'redirection' => 3,
]);

$handlerStack = new HandlerStack($wpHandler, [
    Middleware::factory(Middleware\PrepareBody::class)
]);

$client = new WpClient($handlerStack, 'https://base-url.com/api');

/*-----------------------------------------------------------------------------
 * For a zero-middleware configuration, you can simply pass the base handler
 */

$client = new WpClient($wpHandler, 'https://base-url.com/api');

use RebelCode\WordPress\Http\WpHandler;
use RebelCode\Psr7\Request;

$client = new WpClient(new WpHandler(), 'https://base-url.com/api');

$request = new Request('GET', '/users');
$response = $client->sendRequest($request);

use Psr\Http\Message\RequestInterface;
use Psr\Http\Message\ResponseInterface;
use RebelCode\WordPress\Http\Middleware;

class MyMiddleware extends Middleware {
    public function __construct(HandlerInterface $handler, $arg1, $arg2) {
        parent::__construct($handler);
        // ...
    }

    /** @inheritDoc*/
    public function handle(RequestInterface $request) : ResponseInterface{
        // Do something with the request
        $newRequest = $request->withHeader('X-Foo', 'Bar');
        
        // Delegate to the next handler
        $response = $this->next($newRequest);
        
        // Do something with the response and return it
        return $response->withHeader('X-Baz', 'Qux');
    }
}

$stack = new HandlerStack($baseHandler, [
    function ($handler) {
        return new MyMiddleware($handler, $arg1, $arg2);
    }
]);

$stack = new HandlerStack($baseHandler, [
    Middleware::factory(MyMiddleware::class, [$arg1, $arg2]),
]);