Search code examples
phpyii2

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 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.

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


Solution

  • 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 app\components;
    class MyGlobalClass extends \yii\base\Component{
        public function init() {
            echo "Hi";
            parent::init();
        }
    }
    

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

    'components' => [
        'MyGlobalClass'=>[
            'class'=>'app\components\MyGlobalClass'
         ],
         //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 \yii\base\Object instead of \yii\base\Component