Reputation: 306
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?
Upvotes: 0
Views: 681
Reputation: 22174
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,
],
];
}
Upvotes: 3