如何制作服务提供商或特质将Algolia整合到我的Laravel控制器中?

Kio*_*iow 1 traits service-provider laravel algolia

我正在使用Algolia搜索客户端PHP用于Laravel ,我想在没有Laravel Scout的情况下使用它.

现在我必须在每个需要使用Algolia的控制器中执行此操作:

$client = new \AlgoliaSearch\Client('xxx', 'xxx');

$index = $client->initIndex('index');

$index->doSomeAlgoliaFunction();
Run Code Online (Sandbox Code Playgroud)

如何将其变成服务提供商,这样我每次需要时都不需要初始化Algolia?

Jul*_*eau 5

我建议你将它绑定到容器.在你App\Providers\AppServiceProviderregister方法中:

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');
        });
    }
}
Run Code Online (Sandbox Code Playgroud)

然后,如果你在控制器中需要它,你可以在构造函数上使用typehint它,Laravel将自动传递客户端的实例.

use AlgoliaSearch\Client;

class Controller extends BaseController
{
    use AuthorizesRequests, DispatchesJobs, ValidatesRequests;

    protected $client;

    public function __contruct(Client $client)
    {
       $this->client = $client;
    }

}
Run Code Online (Sandbox Code Playgroud)

如果您在其他地方需要它,可以使用app()辅助函数从容器中获取它.

use AlgoliaSearch\Client;

class Something
{

    public function doMagic()
    {
        $algoliaIndex = app(Client::class)->initIndex('my_index_name');

        $algoliaIndex->addObject(....);
    }

}
Run Code Online (Sandbox Code Playgroud)

注意从中获取凭据,config()或者env()避免提交ADMIN api密钥.