I have read and attempted to apply the answers to all similar questions. I am missing some key concept, or even attempting a solution in the completely wrong way.
Here is the breakdown of what I'm essentially trying to do:
- Bind a singleton in service providers.
public function register()
{
$this->app->singleton(RandomApi::class, function () {
return new RandomApi();
});
}
In the RandomApi class itself, it makes a call and retrieves an access token, and sets it such as
$this->accessToken
.In a controller, I am type hinting this class such as
someMethod(RandomApi $randomApi)
in a couple methods. I then check the output of $randomApi->accessToken, and I want it to persist and keep the 1 generated in the binding or 1st instance, however it is continually constructed and generates a new one everytime.
I have tried all the other stackoverflow suggestions on this topic but nothing seems to be working. Am I going about this in completely the wrong way? Is there another better way to retrieve and store access tokens accross a laravel application? Only generating new ones if the single instance in charge of handling the api sees its token expires?
Thank you!
Edit: example of my RandomApi class:
namespace App\Services;
class RandomApi
{
protected $url = "https://afakeURL.com";
protected $clientId = 'sdfgsdfgsdfgsdfgsdfg';
protected $clientSecret = 'sdfgsdfgsdfgsdfgsdfg';
protected $accessToken;
protected $client;
public function __construct()
{
$this->client = new \GuzzleHttp\Client([
'base_uri' => $this->url,
]);
$this->getAccessToken();
}
protected function getAccessToken ()
{
$response = $this->client->request('POST', "/api/token", [
'headers' => [
'Authorization' => 'Basic '.base64_encode($this->clientId.':'.$this->clientSecret)
],
'form_params' => [
'grant_type' => 'client_credentials'
]
]);
$this->accessToken = json_decode($response->getBody()->getContents())->access_token;
}