Method Injection in Controller


I am struggling making DI work in Yii. I am not sure what I am missing. Basically, I added the method:

   public function actionDs(DatasourceInterface $db)  

and also added in config/web.php

'container' => [

        'singletons' => [

            'app\Contracts\DatasourceInterface' => [

                'class' => 'app\models\Datasource1',




And what I get as result is: Missing required parameters: db

Now, if I do

 $db = Yii::$container->get('DatasourceInterface') 

I get an instance of my Datasource1, which is correct, yet not DI.

I really look forward to understanding how this works :)


Furthermore, if I try to inject it in the constructor, I get this different error:

class SiteController extends Controller


    protected $ds;

    public function __construct(DatasourceInterface $ds)


        $this->ds = $ds;





As I mentioned before, the interface dependency was declared in the web.php file and it actually works if I create the object out of the container manually.

PHP Recoverable Error – yii\base\ErrorException

Argument 1 passed to app\controllers\SiteController::__construct() must implement interface app\Contracts\DatasourceInterface, string given

I really hope someone can help.


DI doesn’t magically inject into controller actions. As for constructor, you seem to have changed constructor signature significantly. It should be, as far as I can see:

__construct($id, $module, $config = [], DatasourceInterface $ds)

1 Like

Thanks Sam