2

データベースに 2 つのテーブルを作成しました。1 つはユーザー用、もう 1 つはセッション用です。最後のアクティビティをセッションに保存しても問題ないと思っていましたが、セッションが削除されていて、どういうわけか最後のアクティビティを保存できないことがわかりました。最後のアクティビティをどこかに保存したいので、約 5 分でユーザー テーブルに保存する方法が必要です。CodeIgniter がセッション データを変更するのと同じです。

それで、それを行う方法は?

4

1 に答える 1

7

セッションテーブルは忘れて、リクエストごとにユーザーテーブルを更新してください。ベースコントローラーのコンストラクターでこれを行うと、自動的に実行されます (これに慣れていない場合は、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
    }

}

代わりに、ログインしたユーザー user を最初に取得した場所と同じ場所でこれを実行できる場合があります。

于 2013-06-28T18:41:05.297 に答える