简体   繁体   English

Yii获取当前登录用户

[英]Yii get current logged user

To get current user I use Yii::app()->user->name it's ok when I'm logged as a user. 为了获得当前用户,我使用Yii::app()->user->name ,当我以用户身份登录时可以。

But when cron job executin command and try Yii::app()->user->name it's get Property "CConsoleApplication.user" is not defined.. 但是,当cron job executin命令尝试使用Yii::app()->user->name它的属性“ CConsoleApplication.user”未定义。

How to get check inside my method does Yii::app() user os defined 如何在我的方法中获取检查, Yii::app() user定义操作系统

I'm try use isset() but still getting same error. 我尝试使用isset()但仍然收到相同的错误。

The thing is, you can't use CWebUser in console application. 问题是,您不能在控制台应用程序中使用CWebUser。

If you rely on a component, which needs CWebUser, you'll have to detect this in the component and create some kind of workaround for this case. 如果依赖于需要CWebUser的组件,则必须在组件中检测到这一点,并为这种情况创建某种解决方法。 For example, you could genereate in your scope code an exception part where ensures that Yii::app()->user is not called: 例如,您可以在范围代码中生成一个例外部分,以确保不调用Yii::app()->user

 public function scopes(){
         if (Yii::app() instanceof CConsoleApplication) {
              $user = array(''); //no condition 
         }else{
              $user = array(
                        'condition'=>'id='.Yii::app()->user->id, 
                      );
         }
         return array(
              'user'    => $user,
              'active'  => array(
                                   'condition'=>'status='.self::STATUS_ACTIVE,
                           ), ...
         );
 }

Another simple isset() check that works for me: 另一个简单的isset()检查对我有用:

if (!isset(Yii::app()->user))
        echo "username not set\n";
return;

Console output: 控制台输出:

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM