【发布时间】: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