fun*_*ein 5 php ioc-container type-hinting laravel laravel-5
所以我想我会尝试在 Laravel 中实际使用这个花哨的 IoC 容器。我从 Guzzle 开始,但我无法让它工作。也许我的理解有差距。我真的很感谢这里的任何帮助。
所以我有一个用于连接到 RESTful Api 的类。这是其中的一个示例:
use GuzzleHttp\Exception\BadResponseException;
use GuzzleHttp\Client;
use GuzzleHttp\Subscriber\Oauth\Oauth1;
class EtApi {
//you can pass in the model if you wanna
//protected $model;
//client Id
protected $clientId;
//client secret
protected $clientSecret;
//base_uri
protected $getTokenUri;
protected $client;
//build
function __construct(Client $client)
{
$this->client = $client;
$this->clientId = 's0m3R4nd0mStr1nG';
$this->clientSecret = 's0m3R4nd0mStr1nG';
$this->getTokenUri = 'https://rest.api/requestToken';
$this->accessToken = $this->getToken($this->clientId, $this->clientSecret, $this->getTokenUri);
}
Run Code Online (Sandbox Code Playgroud)
}
我已经成功安装并使用了 Guzzle,方法是在 $client = new Client(); 之类的方法中手动更新它。但这不是很干,也不是正确的做事方式。所以我在 app\Providers\GuzzleProvider.php 创建了一个 ServiceProvider。我确保这是在 app/config/app.php 下注册的$providers = ['App\Providers\GuzzleProvider']。这是提供者代码:
<?php namespace App\Providers;
use Illuminate\Support\ServiceProvider;
use GuzzleHttp\Client;
use GuzzleHttp\Subscriber\Oauth\Oauth1;
class GuzzleProvider extends ServiceProvider {
/**
* Bootstrap the application services.
*
* @return void
*/
public function boot()
{
//
}
/**
* Register the application services.
*
* @return void
*/
public function register()
{
//
$this->app->bind('Client', function () {
return new Client;
});
}
}
Run Code Online (Sandbox Code Playgroud)
因此,当我尝试访问在实例化 (__construct) 期间加载失败并出现以下错误的 EtApi 方法时。
ErrorException in EtApi.php line 23:
Argument 1 passed to App\EtApi::__construct() must be an instance of GuzzleHttp\Client, none given, called in /home/vagrant/webdocs/et_restful_test/app/Http/Controllers/EtConnectController.php on line 23 and defined
Run Code Online (Sandbox Code Playgroud)
你们中的任何一个 Laravel Master 知道为什么我不能使用这段代码绑定 Guzzle 而 Laravel 的魔法只会将 obj 注入构造函数吗?[docs 1说我应该能够做到这一点。我肯定错过了什么。谢谢你!
根据您问题中的信息很难确定,但基于此
传递给 App\EtApi::__construct() 的参数 1 必须是 GuzzleHttp\Client 的实例,没有给出,在第 23 行 /home/vagrant/webdocs/et_restful_test/app/Http/Controllers/EtConnectController.php 中调用并定义
听起来您是App\Eti在第 23 行直接实例化您的类,EtConnectController.php代码如下所示
$api = new App\EtApi;
Run Code Online (Sandbox Code Playgroud)
如果是这样的话,那么您就缺少 Laravel 依赖注入的关键部分。Laravel 无法更改标准 PHP 的行为 - 即,如果您使用 PHP 的内置new关键字创建一个新类,那么 Laravel 永远不会进行更改以在__construct.
如果你想利用依赖注入,你还需要通过 Laravel 的应用程序容器实例化你的对象。有很多不同的方法可以做到这一点——这里有两种
//$api = new App\EtApi;
\App::make('App\EtApi'); //probably "the right" way
$api = app()['App\EtApi']
Run Code Online (Sandbox Code Playgroud)
如果您这样做,Laravel 将读取类型提示__construct并尝试为您的对象注入依赖项。
| 归档时间: |
|
| 查看次数: |
5844 次 |
| 最近记录: |