在任何控制器的任何操作之前执行我的代码 [英] Execute my code before any action of any controller

查看:26
本文介绍了在任何控制器的任何操作之前执行我的代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想检查我的用户是否在他的个人资料中填写了某些字段,然后才能访问任何控制器的任何操作.例如

I would like to check if my user have filled certain fields in his profile before he can access any action of any controller. For example

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

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

In yii1 I could do it in protected\components\Controller.php in init() function But in yii2 I'm not sure where to put my code. I cannot modify core files, but not sure what to do in backend of my advanced application to make it work.

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

I know I can user beforeAction() but I have too many controllers to do that and to keep track of every controller

推荐答案

如果你需要在每个控制器和动作之前执行一段代码,你可以这样做:

In case you need to execute a code before every controller and action, you can do like below:

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

1 - Add a component into your components directory, for example(MyGlobalClass):

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

2 - 将 MyGlobalClass 组件添加到配置文件中的组件数组中:

2 - Add MyGlobalClass component into your components array in config file:

'components' => [
    'MyGlobalClass'=>[
        'class'=>'app\components\MyGlobalClass'
     ],
     //other components

3 - 将 MyGlobalClass 添加到配置文件中的 bootstarp 数组中:

3 - Add MyGlobalClass into bootstarp array in config file:

'bootstrap' => ['log','MyGlobalClass'],

现在,您可以在每次操作之前看到 Hi.

Now, you can see Hi before every action.

请注意,如果你不需要使用EventsBehaviors,你可以使用\yii\base\Object而不是 \yii\base\Component

Please note that, if you do not need to use Events and Behaviors you can use \yii\base\Object instead of \yii\base\Component

这篇关于在任何控制器的任何操作之前执行我的代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆