简体   繁体   中英

Yii2 - DI injection via method signature

I try to implement controller action injection in Yii2 Framework (version 2.0.15). Here is my code for controller action:

public function actionTerms(Affiliate $affiliate)
{
    // action code
}

Register a dependency in common/components/config/bootstrap.php

$container = Yii::$container;
$container->set('\common\components\Affiliate', '\common\components\Affiliate');

As as result I get error message:

Missing required parameters: affiliate

How to solve this?

Yii 2 does not support dependency injection in action methods. Action parameters are reserved only for GET params.

If you want to use dependency injection in action, you should use standalone action as separate class:

class AffiliateAction extends Action {

    private $affiliate;

    public function __construct(string $id, Controller $controller, Affiliate $affiliate, array $config = []) {
        $this->affiliate = $affiliate;
        parent::__construct($id, $controller, $config);
    }

    public function run() {
        // do something with $this->affiliate
    }
}

Then attach it to controller:

public function actions() {
    return [
        'affiliate' => [
            'class' => AffiliateAction::class,
        ],
    ];
}

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