dongtan1009 2016-02-05 20:17
浏览 1236
已采纳

在所有后端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?

  • 写回答

2条回答 默认 最新

  • doumi1884 2016-02-05 21:53
    关注

    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;
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 运筹学中在线排序的时间在线排序的在线LPT算法
  • ¥30 求一段fortran代码用IVF编译运行的结果
  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集
  • ¥15 lammps拉伸应力应变曲线分析
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛
  • ¥15 请问Lammps做复合材料拉伸模拟,应力应变曲线问题
  • ¥30 python代码,帮调试,帮帮忙吧