簡體   English   中英

Laravel 4:具有獨特訪問者計數的Cookie

[英]Laravel 4 : Cookies for unique visitor count

我正在創建一個簡單的博客,用戶可以在其中添加,更新和查看帖子 我已經在帖子中實現了視圖計數功能,該功能顯示了該帖子的視圖數量 為此,我所做的是:

  1. 創建了一個事件監聽器:

    Event::listen('post.viewed', 'PostHandler@updatePostViewsAction');

  2. 創建了PostHandlerupdatePostViewsAction

     class PostHandler { public function handle() { // } public function updatePostViewsAction( $post ) { // Update view counter of post $post->views_count = $post->views_count + 1; $post->save(); } } 

工作正常,並且視圖計數已成功更新。 但是后來,我決定對觀點進行獨特的計算。 為此,我嘗試使用cookie,即每當他查看帖子並增加views_count,在用戶計算機上創建cookie 如果用戶再次回來查看該帖子,請檢查是否有cookie ,如果有, 則不要增加views_count否則 不要增加 下面是我如何實現此目的:

class PostHandler
{
    public function handle()
    {
        // 
    }

    public function updatePostViewsAction( $post )
    {
        if ( !Cookie::get('post_viewed') ) {
            // Update view counter of post
            $post->views_count = $post->views_count + 1;
            $post->save();
            Cookie::forever('post_viewed', true);
        }
    }
}

但這似乎不起作用,因為views_count每次都會遞增 誰能告訴我,我在這里做錯了什么?

為了使用Laravel保存cookie,您需要將其發送到響應。 但是,您可以通過將cookie發送到隊列來解決此問題。

public function updatePostViewsAction( $post )
{
    if ( !Cookie::get('post_viewed') ) {
        // Update view counter of post
        $post->views_count = $post->views_count + 1;
        $post->save();
        // Create a cookie before the response and set it for 30 days
        Cookie::queue('post_viewed', true, 60 * 24 * 30);
    }
}

來自Laravel Docs http://laravel.com/docs/requests#cookies的來源:

為下一個響應排隊Cookie

如果要在創建響應之前設置Cookie,請使用Cookie :: queue()方法。 Cookie將自動附加到您的應用程序的最終響應中。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM