I have class which requires API Key (APIClent.php).
I want to initialise APIClient.php and share instance (singleton)
I have two controllers that need access to initialised instance (above).
Now each time I call my controller, it's getting new a instance of the class (APIClient) instead of getting an exist one if any.
How do I solve this? This is what my code looks.
AppServiceProvider.php
public function register()
{
$this->app->singleton(APIClient::class, function()
{
return new APIClient(env('API_KEY'));
});
}
ListController.php
public function __construct(APIClient $client)
{
//does the same thing as below
// $this->apiClient = App(APIClient::class);
$this->apiClient = $client;
}
web.php
is just this line
$router->get('lists', ['uses' => 'ListController@index']);
Any tip or resources is appreciated.
Thanks