每个控制器之前的Yii Framework动作

每个控制器之前的Yii Framework动作

问题描述:

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.

是否有任何“主”控制器在文件夹“控制器”中的每个其他控制器之前触发? 我有一个项目,每个用户都有不同的网站语言,所以我想首先检查设置,然后使用以下语言设置语言: p>

  Yii :: $ app->  language ='en-EN'; 
  code>  pre> 
 
 

现在我在每个控制器中都这样做,但我想这应该是一个更容易的选择。 p> div>

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 e.g.:

$config = [
    // ..
    'on beforeRequest' => function($event) {
        Yii::$app->language='en-EN';           
    }
];