我有一個自定義類App/Http/Responder
,它有幾個方法在我的應用程序中構建特定的JSON響應。我想單獨測試我的控制器,所以我試圖通過構造函數注入我的依賴項。Laravel在控制器中找不到IoC綁定
我的計劃是簡單地創建一個服務提供商,重視將其綁定到$app
然後,按照該文檔,讓它可以自動解決:
public function register()
{
$this->app->bind('responder', function()
{
return new App\Http\Responder($this->app['cache'], $this->app['app'], new JsonResponse, $this->app['config']);
});
}
我再加入這個我config/app.php
。
好的,現在我的響應者和它的依賴關係被綁定到應用程序,爲responder
。
現在,我想我能夠注入Responder
到我的控制器構造函數,Laravel將能夠從IoC容器自動解決此問題:
class AreasController extends BaseController {
protected $responder;
public function __construct(Responder $responder)
{
$this->responder = $responder;
}
但是我得到Class Responser does not exist
。
我能得到它的工作,而無需使用App::make()
門面的唯一方法,就是應用程序注入到我的控制器:
use Illuminate\Foundation\Application as App;
class AreasController extends BaseController {
protected $app;
public function __construct(App $app)
{
$this->app = $app;
}
我可以再做$this->app['responder']->method()
。
顯然我錯過了一些東西,但我想遠離在我的應用程序中使用Facades,所以我可以測試。
謝謝...所以現在在我的Responder類構造函數中,我應該只做'__construct($ cache,$ app,$ response,$ config)',因爲它似乎在拋出'Unresolvable dependency解決類App \ Http \ Responder'中的[Parameter#0 [ $ cache]] ...困惑! –
Alias
2014-10-29 20:45:54
確保您註冊了服務提供者,以便IoC容器知道使用綁定來構建它,而不是自動構建具體類。 – 2014-10-29 21:06:00
啊傻了,改了綁定的名字!感謝您花時間! – Alias 2014-10-29 21:15:57