Laravel5.5 统计文章被浏览次数

创建文件:

$ php artisan make:event BlogArticleView
$ php artisan make:listener BlogArticleViewListener

BlogArticleView

app\Events\BlogArticleView.php

<?php

namespace App\Events;

use App\Models\BlogArticle;
use Illuminate\Broadcasting\Channel;
use Illuminate\Queue\SerializesModels;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Broadcasting\PresenceChannel;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;

class BlogArticleView
{
    use Dispatchable, InteractsWithSockets, SerializesModels;

    /**
     * Create a new event instance.
     *
     * @return void
     */
    public function __construct(BlogArticle $article)
    {
        $this->article = $article;
    }

    /**
     * Get the channels the event should broadcast on.
     *
     * @return \Illuminate\Broadcasting\Channel|array
     */
    public function broadcastOn()
    {
        return new PrivateChannel('channel-name');
    }
}

BlogArticleViewListener

app\Listeners\BlogArticleViewListener.php

<?php

namespace App\Listeners;

use App\Events\BlogArticleView;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;

use Illuminate\Session\Store;
use Illuminate\Support\Facades\Cache;

class BlogArticleViewListener
{
    /**
     * Create the event listener.
     *
     * @return void
     */
    public function __construct(Store $session)
    {
        $this->session = $session;
    }

    /**
     * Handle the event.
     *
     * @param  object  $event
     * @return void
     */
    public function handle(BlogArticleView $event)
    {
        $ip = \request()->getClientIp();
        $article = $event->article;
        //先进行判断是否已经 浏览过
        if (!$this->hasViewedArticle($article, $ip)) {
            //保存到数据库
            $article->view_count = $article->view_count + 1;
            $article->save();
            //看过之后将保存到 Session
            $this->storeViewedArticle($article, $ip);
        }
    }

    // 判断是否已经 浏览过
    protected function hasViewedArticle($article, $ip)
    {
        return Cache::has('viewed_Articles_' . $ip. $article->id);
    }
    // 浏览过 之后将保存到 Session
    protected function storeViewedArticle($article, $ip)
    {
        $key = 'viewed_Articles_' . $ip . $article->id;
        // 5 分钟过期
        Cache::put($key, time(), 5);
    }
}

注册 event 事件

app/Providers/EventServiceProvider.php

.
.
.
protected $listen = [
    .
    .
    .
    // 文章浏览数
    'App\Events\BlogArticleView' => [
        'App\Listeners\BlogArticleViewListener',
    ],
];
.
.
.

控制器调用

app/Http/Controllers/BlogArticlesController.php

use App\Events\BlogArticleView;
.
.
.
class BlogArticlesController extends Controller{
    public function show(BlogArticle $article)
    {
        // 更新 文章浏览数
        event(new BlogArticleView($article));
        .
        .
        .
    }
}
.
.
.
讨论数量: 0

请勿发布不友善或者负能量的内容。与人为善,比聪明更重要!