is there any "main" controller which fires before every other controller from folder "controllers"? I have a project where every user has his different site language, so I want to check the setting first and then set the language using:
Yii::$app->language='en-EN';
Right now I do this in every controller I have, but I guess it should be an easier option.
I had same problem while ago, and found a solution by adding another component.
How to load class at every page load in advanced app
Add class in config to components part and load it at start by adding to bootstrap.
config.php
$config = [
// ..
'components' => [
'InitRoutines' => [
'class' => 'app\commands\InitRoutines', // my custom class
],
],
];
$config['bootstrap'][] = 'InitRoutines';
Then make your class to extend Component
with init()
method
InitRoutines.php
namespace app\commands;
use Yii;
use yii\base\Component;
use app\commands\AppHelper;
use app\commands\Access;
class InitRoutines extends Component
{
// this method runs at start at every page load
public function init()
{
parent::init();
Access::checkForMaintenance(); // my custom method
Yii::$app->language = AppHelper::getUserLanguageCode(); // my custom method
}
}
You can attach to the application event beforeAction or beforeRequest and do your stuff here. It seems easier to me eg:
$config = [
// ..
'on beforeRequest' => function($event) {
Yii::$app->language='en-EN';
}
];
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.