Answer the question
In order to leave comments, you need to log in
Where is the best place to initialize a library in Laravel?
Good afternoon. As part of the Laravel project, the library is being used to work with the API. At the moment, I use a "layer": a service of two methods: _construct and getInstance.
class ApiClient
{
protected $api;
public function __construct() {
$this->api = new VeryUsefulApi([
'1' => env('1', false),
'2' => env('2', false),
'3' => env('3', false),
'4' => env('4', false),
]);
}
public function getInstance() {
return $this->api;
}
}
public function __construct(ApiClient $api) {
$this->api= $api;
}
Answer the question
In order to leave comments, you need to log in
use Illuminate\Support\ServiceProvider;
class ApiClientServiceProvider extends ServiceProvider
{
/** @var boolean Отложенный, потому не при каждом запросе нам нужно дергать это апи */
public $deffered = true;
public function register ( )
{
$this->app->singleton(VeryUsefulApi::class, function($app) {
// Не очень хорошо дергать env из провайдера, поэтому поместим-ка настройки в конфиг
// А уж из конфига будем дергать env
new VeryUsefulApi([$app['config']['services.verify_user']);
});
$this->app->singleton(ApiClient::class); // Ну это если нужен именно синглтон
}
/** @return array | string[] Сообщаем контейнеру, что если вдруг нужны эти ключи, то они тут */
public function provides() {
return [VeryUsefulApi::class, ApiClient::class];
}
}
class ApiClient
{
/** @var VeryUsefulApi */
protected $api;
public function __construct (VeryUsefulApi $api)
{
$this->api = $api;
}
#...
}
class SomeController {
/** @var ApiClient */
protected $client;
public fuction __construct(ApiClient $client)
{
$this->clien = $client;
}
}
That's pretty much how it's done. Only it is better to implement VeryUsefulApi into the adapter via DI, otherwise ApiClient is tightly coupled to VeryUsefulApi. But, I guess there are reasons why this is done.
If there are no reasons, then look here how it's done: Laravel's Dependency Injection Container in Depth .
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question