我在数据库中创建了两个表,一个包含用户,另一个包含会话。我原以为将最后一个活动存储到会话中不会有任何问题,但后来我发现会话正在删除,不知何故我无法存储最后的活动。因为我想把最后一个活动存储在某个地方,所以我需要一个解决方案——我如何在大约五分钟内将其保存到用户表中——就像CodeIgniter更改它的会话数据一样。
那么,如何做到这一点呢?
忘记会话表,只需在每次请求时更新users表。我会在基本控制器的构造函数中这样做,这样它就会自动运行(如果您不熟悉,请参阅MY_Controller
示例)。类似这样的东西:
class MY_Controller extends CI_Controller {
public function __construct()
{
parent::__construct():
// The session class is available now because
// we called the parent constructor, where it is already loaded.
// Get the current logged in user (however your app does it)
$user_id = $this->session->userdata('user_id');
// You might want to validate that the user exists here
// If you only want to update in intervals, check the last_activity.
// You may need to load the date helper, or simply use time() instead.
$time_since = now() - $this->session->userdata('last_activity');
$interval = 300;
// Do nothing if last activity is recent
if ($time_since < $interval) return;
// Update database
$updated = $this->db
->set('last_activity', now())
->where('id', $user_id)
->update('users');
// Log errors if you please
$updated or log_message('error', 'Failed to update last activity.');
}
}
若要使用此基本控制器,您将使用其他控制器对其进行扩展。示例:
class SomeController extends MY_Controller {
// MY_Controller constructor runs automatically
function index()
{
// your code
}
}
您可能可以在最初获取登录用户的相同位置执行此操作。