yii2 - 在执行任何 Controller 操作之前执行我的代码

标签 yii2

我想检查我的用户是否可以填写个人资料中的某些字段,然后才能访问任何 Controller 的任何操作。
例如

if(empty(field1) && empty(field2))
{
   header("Location:/site/error")
}

在yii1中,我可以在init()函数中的protected \ components \ Controller.php中完成此操作
但是在yii2中,我不确定将代码放在哪里。我无法修改核心文件,但不确定要在高级应用程序的后端执行什么操作才能使其正常工作。

我知道我可以使用beforeAction(),但是我有太多的 Controller 无法做到这一点并跟踪每个 Controller

最佳答案

如果需要在执行每个 Controller 和操作之前执行代码,可以执行以下操作:

1 -将组件添加到组件目录中,例如(MyGlobalClass):

namespace app\components;
class MyGlobalClass extends \yii\base\Component{
    public function init() {
        echo "Hi";
        parent::init();
    }
}

2 -在配置文件的组件数组中添加MyGlobalClass组件:
'components' => [
    'MyGlobalClass'=>[
        'class'=>'app\components\MyGlobalClass'
     ],
     //other components

3 -在配置文件的MyGlobalClass数组中添加bootstarp:
'bootstrap' => ['log','MyGlobalClass'],

现在,您可以在执行每个操作之前查看Hi

请注意,如果您不需要使用EventsBehaviors,则可以使用\yii\base\Object代替\yii\base\Component

关于yii2 - 在执行任何 Controller 操作之前执行我的代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27180059/

相关文章:

php - Yii 2 更新全部不在

yii2 - yii2如何从多个数组中获取post值

php - 如何在 yii2 queryParams 中设置 OR 条件?

php - Yii2中不同表中两个字段的唯一验证

yii2 - 在 Yii2 的 url 中为静态页面显示子目录名称

php - 我不断收到无效参数编号 : number or bound variables does not math number of tokens in yii2

yii2 - Yii2查询条件存在

php - 如何通过输入特定月份的数据来限制用户,Yii2中存在大于特定月份的记录

gridview - YII2同时多行更新

javascript - 自定义按钮 Action Column, yii2