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

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.

图片转代码服务由CSDN问答提供 功能建议

我创建了一个接口,我正在尝试将其注入到Controller中。 但我收到以下错误:

传递给后端\ controllers \ AgencyController :: __ construct()的参数1必须实现接口common \ service \ AppServiceInterface,string给出< / p>

我在公共文件夹中创建了服务文件夹,在其中添加了两个文件

  • AppService.php
  • AppServiceInterface.php

    现在我在 common / bootstrap.php 文件中定义了这个依赖项,如下所示: / p>

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

    之后我尝试在AgencyController中注入它,它放在backend / controllers / AgencyController里面,如下所示:

      namespace backend \ controllers; 
    use  common \ service \ AppServiceInterface; 
    公共函数__construct(AppServiceInterface $ appService)
     {
     $ this-&gt; appService = $ appService; 
    } 
       
     
     

    但我得到的错误是 前面提到过。

  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

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;
    
    }
    
    已采纳该答案
    打赏 评论

相关推荐 更多相似问题