Last active
August 3, 2021 14:34
-
-
Save kobus1998/c4efc87881902e51aa2d7ffa83323517 to your computer and use it in GitHub Desktop.
simple api abstraction
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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, | |
]); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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