5

我希望在我的大多数视图文件中都有一个变量 $user_profile 可用,而不必在每个控制器文件中创建变量。目前我的工作正常,但我想知道是否有更好的解决方案

我有一些代码来填充变量

$user_profile = YumUser::model()->findByPk(Yii::app()->user->id)->profile;

然后是父类

class Controller extends CController { 

    public function getUserProfile()
    {
      $user_profile = YumUser::model()->findByPk(Yii::app()->user->id)->profile;
    }

}

然后我让所有其他控制器继承 Controller 类,例如

class DashboardController extends Controller
{

public function actionIndex()
{
    $user_profile = parent::getUserProfile();
    $this->render('index', array('user_profile' => $user_profile));

}

}

然后最后在视图文件中我可以简单地访问 $user_profile 变量。

4

3 回答 3

8

在您的基本控制器类中创建类字段:

class Controller extends CController { 
    public $user_profile;

    public function init()
    {
      parent::init();
      $this->user_profile = YumUser::model()->findByPk(Yii::app()->user->id)->profile;
    }
}

不需要直接传过来查看:

public function actionIndex()
{
    $this->render('index');
}

然后您可以使用以下命令在视图中访问它$this

// index.php
var_dump($this->user_profile);
于 2013-07-12T09:34:45.093 回答
2

你已经定义了一个 getter,所以你可以$this->userProfile从你的控制器和你的视图中使用。我只会添加一个缓存逻辑以避免对数据库进行多次查询:

class Controller extends CController
{

    protected $_userProfile=false;

    /*
     * @return mixed a User object or null if user not found or guest user
     */
    public function getUserProfile()
    {
        if($this->_userProfile===false) {
            $user = YumUser::model()->findByPk(Yii::app()->user->id);
            $this->_userProfile = $user===null ? null : $user->profile;
        }
        return $this->_userProfile;
    }
于 2013-07-12T13:28:53.967 回答
0

对于用户个人资料信息,我在登录时使用 setState 填充少量变量来存储数据。

在成功验证后的 UserIdentity 类中,您可以存储类似于以下的数据:

$userRecord = User::model()->find("user_name='".$this->username."'");  
$this->setState('display_name', 
    (isset($userRecord->first_name)) ? 
        $userRecord->first_name : $userRecord->user_name); 

然后在任何视图中,都可以像这样访问它:

echo (isset(Yii::app()->user->display_name) ? 
        Yii::app()->user->display_name : 'Guest');
于 2013-07-12T21:21:08.413 回答