如果用户是Yii的访客,则自动登录


automatically login user if they are guest with Yii

我收到了一些代码,由于遗留的原因,这些代码必须继续使用Yii框架。尽管当用户以访客身份访问某个页面时,我需要该页面自动将他们作为某个用户登录。在浏览了Yii文档和这里之后,我没有找到任何解决这个问题的方法。我想对Yii做的事情可能吗?

我会使用Behaviors来做这件事,可能是在BegnRequest上。这将在处理每个请求之前触发,如果用户当前是访客,则会自动登录

<?php
class BeginRequest extends CBehavior
{
  public function attach($owner)
  {
    $owner->attachEventHandler('onBeginRequest', array($this, 'handleBeginRequest'));
  }
public function handleBeginRequest($event)
{
  if(Yii::app()->user->isGuest())
  {
    $identity = new UserIdentity('known-user', 'known-password');
    // authenticate identity or not, up to you if you know which user should be logged in
    Yii::app()->user->login($identity);
  }       
}