我尝试在Yii2 Framework(版本2.0.15)中实现控制器动作注入。这是我的控制器操作代码:
public function actionTerms(Affiliate $affiliate)
{
// action code
}
在common / components / config / bootstrap.php中注册依赖项
$container = Yii::$container;
$container->set('\common\components\Affiliate', '\common\components\Affiliate');
结果是我收到错误消息:
Missing required parameters: affiliate
如何解决这个问题?
答案 0 :(得分:1)
Yii 2在动作方法中不支持依赖项注入。动作参数仅保留用于GET参数。
如果要在操作中使用依赖项注入,则应将独立操作用作单独的类:
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
}
}
然后将其附加到控制器:
public function actions() {
return [
'affiliate' => [
'class' => AffiliateAction::class,
],
];
}