DI在yii2中,构造函数注入
问题描述:
我创建了一个接口,我试图将它注入到Controller中。但我发现了以下错误:DI在yii2中,构造函数注入
Argument 1 passed to backend\controllers\AgencyController::__construct() must implement interface common\service\AppServiceInterface, string given
我创造了共同文件夹内的文件夹的服务,增加了两个文件,把它
- AppService.php
- AppServiceInterface.php
现在我在common/bootstrap.php
文件中定义了这种依赖关系,如下所示:
Yii::$container->set('common\service\AppServiceInterface',
'common\service\AppService');
后来我试图注入它里面AgencyController其置于后端/控制器/ AgencyController里面象下面这样:
namespace backend\controllers;
use common\service\AppServiceInterface;
public function __construct(AppServiceInterface $appService)
{
$this->appService = $appService;
}
但正如前面所提到的,我发现了错误。
答
所以我不得不改变__construct方法如下图所示,其工作正常:
public function __construct($id, $module, AppServiceInterface $appService , $config = [])
{
parent::__construct($id, $module);
$this->appService = $appService;
}