我正在为 Laravel使用Algolia 搜索客户端 PHP,我想在没有 Laravel Scout 的情况下使用它。
现在,我必须在需要使用 Algolia 的每个控制器中执行此操作:
$client = new \AlgoliaSearch\Client('xxx', 'xxx');
$index = $client->initIndex('index');
$index->doSomeAlgoliaFunction();
我怎样才能把它变成一个服务提供者,这样我就不必每次需要它时都初始化 Algolia?
我建议您将其绑定到容器。在您的App\Providers\AppServiceProvider
, 在register
方法中:
namespace App\Providers;
use AlgoliaSearch\Client;
use Illuminate\Support\ServiceProvider;
class AppServiceProvider extends ServiceProvider
{
public function register()
{
$this->app->singleton(Client::class, function () {
return new Client('xxx', 'xxx');
});
}
}
然后,如果您需要在控制器中使用它,您可以在构造函数中使用 typehint 它,Laravel 将自动传递客户端的实例。
use AlgoliaSearch\Client;
class Controller extends BaseController
{
use AuthorizesRequests, DispatchesJobs, ValidatesRequests;
protected $client;
public function __contruct(Client $client)
{
$this->client = $client;
}
}
如果你在其他地方需要它,你可以使用app()
辅助函数从容器中获取它。
use AlgoliaSearch\Client;
class Something
{
public function doMagic()
{
$algoliaIndex = app(Client::class)->initIndex('my_index_name');
$algoliaIndex->addObject(....);
}
}
注意从config()
或获取凭据env()
,避免提交您的 ADMIN api 密钥。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句