【问题标题】:Using Laravel Service Provider for passing constructor parameter使用 Laravel 服务提供者传递构造函数参数
【发布时间】:2016-01-11 07:46:56
【问题描述】:

我正在尝试使用 laravel 服务提供者来注入依赖项。

namespace App\ABC\Services;

use Exception;
use App\ABC\Models\Nsme;
use GuzzleHttp\Client;
use Illuminate\Http\Response;

class NsmeService
{

    /**
     * GuzzleHttp client
     *
     * @var $httpClient
     */
    protected $httpClient;

    /**
     * Create a new service instance.
     *
     * @param Nsme $nsme
     */
    public function __construct(Nsme $nsme)
    {
        $this->httpClient = $httpClient;
    }

    public function doApiCall() {
        new Client(['base_uri' => 'http://sso.myapiservice.com']);
    }   
}

在上面的类中,我想修改 doApiCall 以使用服务 laravel 提供者。

我的服务提供者是这样写的。

namespace App\ABC\Providers;

use Illuminate\Support\ServiceProvider;
use GuzzleHttp\Client;

class HttpClientServiceProvider extends ServiceProvider
{
    /**
     * Indicates if loading of the provider is deferred.
     *
     * @var bool
     */
    //protected $defer = false;

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

    /**
     * Register the application services.
     *
     * @return void
     */
    public function register()
    {
       $this->app->bind('GuzzleHttp\Client', function()
        {
            return new Client(['base_uri' => 'http://sso.testserver.com']);
        });
    }   

然后我像这样修改了 doApiCall() 方法

public function doApiCall() {
    $client = app('Client');
}   

但这不起作用。基本上我想传递一些构造函数参数,所以我不能将 Client 类作为 NsmeService 类中的构造函数参数传递。有什么想法吗?

【问题讨论】:

    标签: laravel-5


    【解决方案1】:

    试试这个。

    $client = app('GuzzleHttp\Client');
    

    您像GuzzleHttp\Client 一样绑定服务,但像Client 一样调用。 为避免此类错误,您可以使用\GuzzleHttp\Clint::class

    另外,不要忘记注册您的服务提供商:)

    【讨论】:

    • 我试过了,但是使用这个时没有设置“base_uri” :(。所以我认为构造函数参数没有设置。
    • 尝试更改服务名称,例如改为$this->app->bind('ApiClient'
    猜你喜欢
    • 2017-02-11
    • 1970-01-01
    • 2015-10-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-24
    • 2018-05-24
    • 1970-01-01
    相关资源
    最近更新 更多