Skip to content

Instantly share code, notes, and snippets.

@kobus1998
Last active August 3, 2021 14:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kobus1998/c4efc87881902e51aa2d7ffa83323517 to your computer and use it in GitHub Desktop.
Save kobus1998/c4efc87881902e51aa2d7ffa83323517 to your computer and use it in GitHub Desktop.
simple api abstraction
<?php
class MyApiClient
{
use Requestor;
const VERSION = 'v1';
/** @var GuzzleHttp\Client */
private $client;
private $url;
public function __construct(GuzzleHttp\Client $client = null)
{
$this->client = $client ?? new GuzzleHttp\Client;
$this->url = 'http://localhost:6969/api/' . self::VERSION;
}
protected function request($method, $path, $body = null): Psr\Http\Message\ResponseInterface
{
return $this->client->request(strtoupper($method), "{$this->url}{$path}", [
'body' => $body ?? null,
]);
}
}
<?php
trait Requestor {
abstract protected function request($method, $path, $body = null): Psr\Http\Message\ResponseInterface;
public function post($path, $body = []): Psr\Http\Message\ResponseInterface
{
return $this->request('POST', $path, $body);
}
public function put($path, $body = null): Psr\Http\Message\ResponseInterface
{
return $this->request('PUT', $path, $body);
}
public function get($path): Psr\Http\Message\ResponseInterface
{
return $this->request('GET', $path);
}
public function delete($path): Psr\Http\Message\ResponseInterface
{
return $this->request('DELETE', $path);
}
}
<?php
use GuzzleHttp\Client;
use GuzzleHttp\HandlerStack;
use GuzzleHttp\Middleware;
$container = [];
$history = Middleware::history($container);
$stack = HandlerStack::create();
$stack->push($history);
$client = new Client([
'handler' => $stack
]);
$response = (new MyApiClient($client))->post('/user/1', [
'email' => 'foo@bar.com'
]);
echo $response->getStatusCode(); // 201
$container; // request history for e.g. logging
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment