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

标签 php laravel dependency-injection

这是我的服务提供商:

<?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/

相关文章:

php - 在插入之前插入单引号

php - sql left join 不工作

git - pull pull 维尔 5 : Remove development dependancies from app config file

java - 加载静态属性文件类

c# - 依赖注入(inject)到 {get;设置;} 属性

PHP SQL 意外的 T_STRING 错误

php - 使用 Laravel Eloquent 进行缓慢的 MySQL 查询

php - Laravel模型对象检索关系模型与where条件没有 "get"方法

c# - 在 ASP.NET MVC 4 解决方案中配置编译时依赖注入(inject)的依赖倒置

php - 我使用循环填充 <select> 选项,如何使选择框显示当前选项而不是最高值?