Skip to content

Instantly share code, notes, and snippets.

@tdomarkas
Last active July 11, 2021 11:59
Show Gist options
  • Save tdomarkas/c8601d85b5950e831aec95068883263e to your computer and use it in GitHub Desktop.
Save tdomarkas/c8601d85b5950e831aec95068883263e to your computer and use it in GitHub Desktop.
HTTPlug client (with basic auth)
composer require psr/http-client nyholm/psr7
<?php
class Service
{
/** @var Psr\Http\Client\ClientInterface */
private $client;
/** @var Psr\Http\Message\RequestFactoryInterface */
private $requestFactory;
/** @var Psr\Http\Message\StreamFactoryInterface */
private $streamFactory;
public function __construct(
Psr\Http\Client\ClientInterface $client,
Psr\Http\Message\RequestFactoryInterface $requestFactory,
Psr\Http\Message\StreamFactoryInterface $streamFactory
) {
$this->client = $client;
$this->requestFactory = $requestFactory;
$this->streamFactory = $streamFactory;
}
public function doStuff(): void
{
$this->client->sendRequest(
$this->requestFactory
->createRequest('POST', '/api')
->withBody($this->streamFactory->createStream('{"foo":"bar"}'))
);
}
}
services:
Psr\Http\Client\ClientInterface: '@httplug.psr18_client.default'
Psr\Http\Message\RequestFactoryInterface: '@httplug.psr17_request_factory.default'
Psr\Http\Message\StreamFactoryInterface: '@httplug.psr17_stream_factory.default'
Psr\Http\Message\UriFactoryInterface: '@httplug.psr17_uri_factory.default'
Psr\Http\Client\ClientInterface.api_provider:
public: true
class: Http\Client\Common\PluginClient
arguments:
- '@Psr\Http\Client\ClientInterface'
-
- !service
class: Http\Client\Common\Plugin\AuthenticationPlugin
arguments: [ !service { class: Http\Message\Authentication\BasicAuth, arguments: [ 'user', 'password' ] } ]
- !service
class: Http\Client\Common\Plugin\BaseUriPlugin
arguments:
- !service
class: Psr\Http\Message\UriFactoryInterface
factory: ['@Psr\Http\Message\UriFactoryInterface', 'createUri']
arguments: ['http://localhost/api']
- { replace: true }
Service:
arguments:
- '@Psr\Http\Client\ClientInterface.api_provider'
- '@Psr\Http\Message\RequestFactoryInterface'
- '@Psr\Http\Message\StreamFactoryInterface'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment