Image for post: Do something before every action in a controller on Yii 2

Do something before every action in a controller on Yii 2

To do something before a controller is loaded is a common problem to all MVC frameworks. On Yii 2 you can use the beforeAction method for a single controller but if you need to do a something before every controller, you have to use the config/main.php file. I use this technique to register meta tags for every page but you can do whatever you need:

...'on beforeAction' => function($event) use($appName) { Yii::$app->view->registerMetaTag([ 'name' => 'robots', 'content' => 'noodp' ], 'robots'); return $event;},

I hope this will be helpful.