Skip to content

Instantly share code, notes, and snippets.

@willchambers99
Last active February 26, 2020 10:01
Show Gist options
  • Save willchambers99/a5b7ad0ed4000560a550e7f7b5987dd8 to your computer and use it in GitHub Desktop.
Save willchambers99/a5b7ad0ed4000560a550e7f7b5987dd8 to your computer and use it in GitHub Desktop.
Example PHP service that can be used to implement an API.
<?php
namespace App\Services;
use Illuminate\Support\Facades\Log;
use Http\Factory\Discovery\HttpClient;
use WillChambers\Api\SomeApi;
use WillChambers\Configuration;
class DatastoreService
{
protected $psr18Client;
protected $api;
public function getApi(): SomeApi
{
$client = $this->getClient();
$config = new Configuration(
[
'syncClient' => $client,
]
);
$config = $config->withAccessToken(
// EXAMPLE "bearer token"
config('services.api.secret')
)->withHost(
// EXAMPLE "https://localhost:5080/api/v1"
config('services.api.endpoint') -
);
$this->api = new SomeApi(
$config
);
return $this->api;
}
public function getClient()
{
if (!$this->psr18Client) {
$this->psr18Client = HttpClient::client();
}
return $this->psr18Client;
}
public function createSomething($requestBody)
{
$api = $this->getApi();
return $api->createSomething($requestBody);
}
public function getSomething(string $string)
{
$api = $this->getApi();
return $api->getSomething($string);
}
public function searchSomething($limit = null, $offset = null, $query = null)
{
$api = $this->getApi();
return $api->searchSomething($limit, $offset, $query);
}
public function updateSomething($item, $requestBody)
{
$api = $this->getApi();
return $api->updateSomething($item, $requestBody);
}
public function deleteSomething($item)
{
$api = $this->getApi();
return $api->deleteSomething($item);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment