doubu7134 2014-10-28 13:13
浏览 36

Yii 1.1:跨控制器变量(甚至是交叉控制变量)

For each request I have to load or, at least, create instance of a MyUser, which contains username, some internal permissions info, link to avatar and so on.

The thing is that I need this info for each and every controller and, for most of the views (to render or not to render some controls depending on user status and permissions).

It sounds like the need for a global variable, created at the time request being handled. What is the best way to solve this problem?

  • 写回答

2条回答 默认 最新

  • dongwei1954 2014-10-28 13:36
    关注

    Override CWebUser (which is what you call when you issue Yii::app()->user) with your custom class WebUser (placed in the components or other folder that has it's classes autoincluded), and define some getters like it is done with getRole() example below:

    <?php
    class WebUser extends CWebUser {
        private $_model = null;
        function getRole() {
            if($user = $this->getModel()){
              return $user->userRole->name;
            }
        }
        private function getModel(){
            if (!$this->isGuest && $this->_model === null){
              $this->_model = User::model()->findByPk($this->id);
            }
            return $this->_model;
        }   
    }
    

    If you user the custom class instead of CWebUser, you have to explicitly tell which class to use in application's config:

    'user'=>array(
        'class' => 'WebUser',
        // …
    ),
    
    评论

报告相同问题?

悬赏问题

  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器