简体   繁体   中英

DI in yii2, constructor injection

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.

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;

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM