Skip to main content

Register a Custom Driver

use Cognesy\Http\Config\HttpClientConfig;
use Cognesy\Http\Contracts\CanHandleHttpRequest;
use Cognesy\Http\Creation\HttpClientDriverFactory;
use Psr\EventDispatcher\EventDispatcherInterface;

HttpClientDriverFactory::registerDriver(
    'acme',
    static function (HttpClientConfig $config, EventDispatcherInterface $events): CanHandleHttpRequest {
        return new AcmeHttpDriver($config, $events);
    }
);
// @doctest id="1c13"

Build Client with Custom Driver

use Cognesy\Http\Config\HttpClientConfig;
use Cognesy\Http\Creation\HttpClientBuilder;

$client = (new HttpClientBuilder())
    ->withConfig(new HttpClientConfig(driver: 'acme'))
    ->create();
// @doctest id="b14e"

Register a Custom Pool Handler (Optional)

use Cognesy\Http\Config\HttpClientConfig;
use Cognesy\Http\Contracts\CanHandleRequestPool;
use Cognesy\Http\Creation\HttpClientDriverFactory;
use Psr\EventDispatcher\EventDispatcherInterface;

HttpClientDriverFactory::registerPoolHandler(
    'acme',
    static function (HttpClientConfig $config, EventDispatcherInterface $events): CanHandleRequestPool {
        return new AcmePoolHandler($config, $events);
    }
);
// @doctest id="62be"
Register this when your custom driver should support HttpClient::pool(). If you skip this, pool() fails for that custom driver.

Reuse Existing Vendor Clients

use Cognesy\Http\Creation\HttpClientBuilder;
use Symfony\Component\HttpClient\HttpClient as SymfonyHttpClient;

$client = (new HttpClientBuilder())
    ->withClientInstance('symfony', SymfonyHttpClient::create())
    ->create();
// @doctest id="1723"

Direct Driver Injection (No Global Registration)

use Cognesy\Http\Creation\HttpClientBuilder;

$client = (new HttpClientBuilder())
    ->withDriver($myDriver) // CanHandleHttpRequest
    ->withPoolHandler($myPoolHandler) // CanHandleRequestPool (optional)
    ->create();
// @doctest id="2250"

See Also