gpt4 book ai didi

php - Laravel:为什么在实例化其提供的类时不调用已注册的服务提供者?

转载 作者:行者123 更新时间:2023-12-01 13:30:25 25 4
gpt4 key购买 nike

这是我的服务提供商:

<?php

namespace App\Providers;

use Illuminate\Support\Facades\Config;
use Illuminate\Support\ServiceProvider;

class ESServiceProvider extends ServiceProvider
{
/**
* Bootstrap the application services.
*
* @return void
*/
public function boot()
{
//
}

/**
* Register the application services.
*
* @return void
*/
public function register()
{
$this->app->singleton('\Elastica\Search', function ($app) {
$client = new \Elastica\Client(array(
'host' => env('ES_HOST'),
'port' => env('ES_PORT')));
$search = new \Elastica\Search($client);
$search->addIndex(Config::get('constants.es_index'))->addType(Config::get('constants.es_type'));
return $search;
});
}
}

当注入(inject) \Elastica\Search\ 的实例时,闭包(singleton() 的第二个参数)不会被调用(使用 var_dump() 验证) /dd())。提供商已正确注册 - 已按上述方式验证。为什么?

最佳答案

原因是,在 Laravel 5.4 及更高版本中,singleton()(以及类似的绑定(bind)函数)的第一个参数不能有前导斜杠。因此,将其更改为 'Elastica\Search' 可以解决问题。我花了大约一个小时的调试时间才意识到这一点——希望这篇文章这次能救人……

解释此更改的 Laravel 网站帖子:http://laravel-guide.readthedocs.io/en/latest/upgrade/ - 搜索 Binding Classs With Leading Slashes

关于php - Laravel:为什么在实例化其提供的类时不调用已注册的服务提供者?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46237058/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com