doumi4676 2016-11-10 11:13
浏览 86
已采纳

DI在yii2中,构造函数注入

I have created an interface, I'm trying to inject it inside Controller. But I'm getting following error:

Argument 1 passed to backend\controllers\AgencyController::__construct() must implement interface common\service\AppServiceInterface, string given

I created service folder inside common folder, added two files into it

  • AppService.php
  • AppServiceInterface.php

Now I defined this dependency inside common/bootstrap.php file as below:

Yii::$container->set('common\service\AppServiceInterface',
                     'common\service\AppService');

Afterwards I tried to inject it inside AgencyController which is placed inside backend/controllers/AgencyController like below:

namespace backend\controllers;
use common\service\AppServiceInterface;
public function __construct(AppServiceInterface $appService)
{
   $this->appService = $appService;
}

But I'm getting the error as mentioned earlier.

  • 写回答

1条回答 默认 最新

  • drne47241 2016-11-10 11:23
    关注

    So I have to change __construct method like below and its working fine:

    public function __construct($id, $module, AppServiceInterface $appService , $config = [])
    {
        parent::__construct($id, $module);
        $this->appService = $appService;
    
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?