yii get current user id = определить id текущего пользователя

источник = http://www.yiiframework.com/wiki/6/how-t...

чтобы получить id можно ,например. модифицировать стандартный класс (\components\) UserIdentity
который описывает процесс входа в систему для сущности, которую представляет модель "пользователь" (User)

- фактически мы расширим стандартный функционал
который опять же в стандартной форме выглядит так:

<?php

/**
 * UserIdentity represents the data needed to identity a user.
 * It contains the authentication method that checks if the provided
 * data can identity the user.
 */
class UserIdentity extends CUserIdentity
{
	/**
	 * Authenticates a user.
	 * The example implementation makes sure if the username and password
	 * are both 'demo'.
	 * In practical applications, this should be changed to authenticate
	 * against some persistent user identity storage (e.g. database).
	 * @return boolean whether authentication succeeds.
	 */
	public function authenticate()
	{
		$users=array(
			// username => password
			'demo'=>'demo',
			'admin'=>'admin',
		);
		if(!isset($users[$this->username]))
			$this->errorCode=self::ERROR_USERNAME_INVALID;
		else if($users[$this->username]!==$this->password)
			$this->errorCode=self::ERROR_PASSWORD_INVALID;
		else
			$this->errorCode=self::ERROR_NONE;
		return !$this->errorCode;
	}
}

вот что сделаем:

<?php


class UserIdentity extends CUserIdentity
{

         /*создаём приватное поле
             в котором будем хранить id*/
         private $_id; 


	public function authenticate()
	{
		

 $user=User::model()->findByAttributes(array('username'=>$this->username));
        if($user===null)
            $this->errorCode=self::ERROR_USERNAME_INVALID;
        else if($user->password!==md5($this->password))
            $this->errorCode=self::ERROR_PASSWORD_INVALID;
        else
        {
            $this->_id=$user->id; //запоминаем id при входе в систему (ловко)))
            $this->setState('lastLoginTime', $user->lastLoginTime); // запоминаем время последнего захода
            $this->errorCode=self::ERROR_NONE;
        }
        return !$this->errorCode;
	}


/*добавляем метод для обращения к полю _id*/
   public function getId()
    {
        return $this->_id;
    }
}

теперь обратиться к id (и дате последнего входа) вполне можно так:

$id=Yii::app()->user->id;
$lastLoginTime=Yii::app()->user->lastLoginTime;

почему именно так - надо врубаться - в частности врубаться в отношения классов фрэймворка.

ВНИМАНИЕ:
прежде чем модифицировать область авторизации - обязательно выполните "logout" - иначе получите сообщение = lastLoginTime не определён - в этом случае надо перелогиниться

но мне не помогает подобная шняга, поэтому - так как пока не требуется закоментил :

// $this->setState('lastLoginTime', $user->lastLoginTime);

в любом случае - читать надо здесь = http://www.yiiframework.com/wiki/6/how-t...