在所有后端Yii2全局设置参数变量

I have this code in layout/main.php:

    $userId = Yii::$app->user->id;
    $data = User::find()->where('id ="'.$userId.'"')->one();
    $type = $data['type'];
    Yii::$app->view->params['Type'] = $type;

I cant' access $this->params['Type'] from any controller except SiteController. If I navigated using any another controller i got this error:

 PHP Notice – yii\base\ErrorException
 Undefined index: Type

If I duplicated my query in every controller, It works well. But I don't want to do that. How to make it globally at the backend only?

You can definitely accomplish this (without explicitly session coding) successfully by

In your model (User.php)

    /**
     * @inheritdoc
     */
    public static function findIdentity($id)
    {
        // return isset(self::$users[$id]) ? new static(self::$users[$id]) : null;
        $User = static::findOne(['id'=>$id]);
        if(!$User)
        {
            return null;
        }
        else
        {
            $dbUser = 
            [
                'id' => $User->id,
                'image'=>$User->image,
                'type'=>$User->type,
                // 'usertype'=>$User->user_type, set other attributes too
                'username' => $User->username,
                'first_name' => $User->first_name,
                'last_name' => $User->last_name,
                'email' => $User->email,
            ];
            return new static($dbUser);
        }
    }

Now if the user has logged in successfully, then you use all this attributes globally (through out the project For eg in model, view controller) by

For eg

echo Yii::$app->user->identity->id;
echo Yii::$app->user->identity->image;
echo Yii::$app->user->identity->type;
echo Yii::$app->user->identity->username;
echo Yii::$app->user->identity->frst_name;
echo Yii::$app->user->identity->last_name;
echo Yii::$app->user->identity->email;

What about using session :

$session = new \yii\web\Session;
$session->open();
$value1 = $session['name1'];  // get session variable 'name1'
$value2 = $session['name2'];  // get session variable 'name2'
foreach ($session as $name => $value) // traverse all session variables
$session['name3'] = $value3;  // set session variable 'name3'

See docs for more details.