How to decorate my API clients - need input
Hey guys,
I'm trying to figure out the best/most flexible way to decorate my API client. I have an application that wraps multiple third-party APIs, some of them use OAuth2 while others use REST etc.
namespace App\Integrations\Apis\Platforms;
use App\Integrations\Apis\Contracts\Account;
abstract class AbstractPlatform implements Account
{
/**
* The account model of a platform.
*
* @var \App\Platform
*/
protected $account;
/**
* Set platform account model
*
* @param \App\Platform $account
* @return $this
*/
public function with($account)
{
$this->account = $account;
return $this;
}
}
<?php
namespace App\Integrations\Apis\Platforms;
use App\Integrations\Apis\Clients\BingClient;
use App\Integrations\Apis\Contracts\Client;
class BingPlatform extends AbstractPlatform
{
/**
* Client implementation
*
* @var BingClient
*/
protected $client;
public function __construct(Client $client)
{
$this->client = $client;
// set up client if platform account was set
if ($this->account) {
$this->client->setAccountId($this->account->account_id);
}
}
}
ServiceProvider:
// Register contextual bindings
$this->app->when(BingPlatform::class)
->needs(Client::class)
->give(function () {
$config = config('platforms.bing');
return (new BingClient(
$config['client_id'],
$config['client_secret'],
$config['developer_token']
));
});
This is how I instantiate the BingPlatform and pass the account model to it:
$account = PlatformAccount::find(1);
Platform::provider('bing')->with($account);
The account model then has additional fields required to connect to the API, for example account_id, while the app config just has the config required for my app to connect.
The way I am doing it now, would of course work, but it kind of feels wrong to me that I manually set things like $this->client->setAccountId($this->account->account_id); in the BingPlatform.
To reiterate: The app will have multiple Platforms, some require different connections and arguments than others, so I'm trying to make it so that the connection / Client can be flexible.
Is there a better way? I'm unsure how else I could structure it
Please or to participate in this conversation.