Where to record user's last online time...

I would like to record a user’s last online time, which is the last time they loaded a page. But that’s different from logging in, and it’s also different from every access; we have several AJAX functions (such as the chat) which I do not want to trigger that, because that would only slow things down.

The main common denominator that I’ve found is actually the layout page. Any time the layout is loaded, I want the last online time to update, and any time the layout is not loaded, I don’t want it to update. And conveniently enough, I also want it recording where the last action was, which is information the layout can get.

Problem is, that’s a view, and I don’t think a database command belongs in a view. Is there some better place where I should put such a function?

If you are using protected/components/controller.php which every controller of yours implementing from, you can add some code at the method init().

That is to say, you can record the time to the database.

Yep! Controller init() as David is suggesting. For action you may use the ActionId or even parse the HTTP_REFER

If you work in a controller, you can use $this->id and $this->action->id.

You can add this fields to the user table, and then add a method in the model:




public function setLastOnline($controller, $action)

{

   $this->lastTimeOline=new CDbExpression('NOW()');

   $this->lastController=$controller;

   $this->lastAction=$action;

}




And in controller.php:




public function init()

{

    $user= User::model()->findByPk(Yii::app()->user->id);

    $user->setLastOnline($this->id, $this->action->id)

    $user->save();     

    return parent::init();

}



Something like that. If in init id and action are not set, you can use beforeAction()

Well unfortunately, my AJAX calls are still handled with a controller. But, since there are presumably fewer of them than any other controllers, perhaps I could override the init function somehow…

You can use Yii::app()->request->isAjaxRequest to only track on non-ajax requests.