[英]Laravel dependency injection “not instantiable”
I have spent a day trying debugging and trying to understand what is going wrong but... 我花了一天的时间尝试调试并试图了解问题所在,但是...
So here is my code: 所以这是我的代码:
<?php
namespace RememberCalories\Rest;
interface MyJsonResponseInterface
{
public function getResponse();
}
And here is the class which I want to inject: 这是我要注入的类:
<?php
namespace RememberCalories\Rest;
class MyJsonResponse implements MyJsonResponseInterface
{
protected $success;
protected $responseCode;
protected $responseMsg;
protected $data;
public function __construct($data, $responseCode=0, $responseMsg='')
{
$this->data = $data;
$this->responseCode = $responseCode;
$this->responseMsg = $responseMsg;
if ( $this->responseCode === 0 ) {
$this->success = true;
}
}
...
Binding: 捆绑:
\App::bind('MyJsonResponseInterface', function($app, $parameters) {
$obj = new \RememberCalories\Rest\MyJsonResponse(null);
// var_dump($obj);
// die();
return $obj;
});
And at last the controller: 最后是控制器:
<?php
use \RememberCalories\MainMenu\MainMenu;
use \RememberCalories\Repository\TargetEloquentRepository as TargetRepository;
use \RememberCalories\Rest\MyJsonResponseInterface;
//use \RememberCalories\Rest\MyJsonResponse;
class BaseController extends Controller
{
protected $viewVars;
protected $mainMenu;
//Dependency injection classes
protected $target;
protected $myJsonResponse;
public function __construct(TargetRepository $target, MyJsonResponseInterface $myJsonResponse )
{
$this->beforeFilter('accessFilter');
$this->target = $target;
//$this->myJsonResponse = $myJsonResponse;
$this->mainMenu = (new MainMenu())->build();
$this->prepareViewVariables();
}
So the problem is with the second parameter of BaseController: MyJsonResponseInterface. 因此,问题出在BaseController的第二个参数:MyJsonResponseInterface。 The first is injected without problems but this one I get an error: 第一个注入没有问题,但是这个我得到一个错误:
Illuminate \\ Container \\ BindingResolutionException 照亮\\容器\\ BindingResolutionException
Target [RememberCalories\\Rest\\MyJsonResponseInterface] is not instantiable. 目标[RememberCalories \\ Rest \\ MyJsonResponseInterface]无法实例化。
It seems that the Closure in \\App::bind('MyJsonResponseInterface' ...) is not called. 似乎没有调用\\ App :: bind('MyJsonResponseInterface'...)中的Closure。 I have moved it to service provider with the same result. 我已经将其移至服务提供商,其结果相同。
But at the same if to call manually \\App::make('MyJsonResponseInterface')
everything is created ideally. 但是,如果同时手动调用\\App::make('MyJsonResponseInterface')
则理想情况下会创建所有内容。
Please advise what way to investigate. 请告知调查方法。
您需要App::bind
完整的名称空间-因此在您的示例中是App::bind('RememberCalories\\Rest\\MyJsonResponseInterface')
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.