2017-09-15 132 views
2

这是我的服务提供商:Laravel:为什么在实例化其提供的类时未注册注册的服务提供者?

<?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; 
     }); 
    } 
} 

当(使用var_dump()/dd()验证)注入的\Elastica\Search\关闭(第2参数去singleton())不会被调用的情况。提供者已正确注册 - 按上述进行验证。为什么?

回答

2

在Laravel 5.4及以上版本中,原因是singleton()(和类似的绑定函数)的第一个参数不能有前导斜线。因此,将其更改为'Elastica\Search'可以解决问题。我花了大约一个小时的调试来实现这一点 - 希望这篇文章节省了一些人这次...

Laravel网站后解释这个变化:http://laravel-guide.readthedocs.io/en/latest/upgrade/ - 搜索Binding Classes With Leading Slashes

相关问题