Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
523 views
in Technique[技术] by (71.8m points)

yii2 - Execute my code before any action of any controller

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")
}

In yii1 I could do it in protectedcomponentsController.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.

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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

namespace appcomponents;
class MyGlobalClass extends yiiaseComponent{
    public function init() {
        echo "Hi";
        parent::init();
    }
}

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

'components' => [
    'MyGlobalClass'=>[
        'class'=>'appcomponentsMyGlobalClass'
     ],
     //other components

3 - Add MyGlobalClass into bootstarp array in config file:

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

Now, you can see Hi before every action.

Please note that, if you do not need to use Events and Behaviors you can use yiiaseObject instead of yiiaseComponent


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...