69.统计话题浏览量(二)

未匹配的标注

本节说明

  • 对应视频教程第 69 小节:Thread Views: Design #2 - Extract Class

本节内容

上一节我们使用Trait记录了浏览量,这一节我们将记录浏览量的逻辑抽象成特定的类文件。我们需要定义一个类,这样做的好处是,如果以后我们需要记录其他类型数据的浏览量,我们可以很方便的通过这个类来完成。首先我们删除上一节的Trait文件,并新建类文件:
forum\app\Visits.php

<?php

namespace App;

use Illuminate\Support\Facades\Redis;

class Visits
{
    protected $thread;

    public function __construct($thread)
    {
        $this->thread = $thread;
    }

    public function record()
    {
        Redis::incr($this->cacheKey());

        return $this;
    }

    public function reset()
    {
        Redis::del($this->cacheKey());

        return $this;
    }

    public function count()
    {
        return Redis::get($this->cacheKey()) ?: 0;
    }

    public function cacheKey()
    {
        return "threads.{$this->thread->id}.visits";
    }
}

我们将记录浏览量跟获取浏览量的逻辑放到了Visits类中,接下来我们需要修改模型文件:
forum\app\Thread.php

<?php

namespace App;

use App\Events\ThreadReceivedNewReply;
use Illuminate\Database\Eloquent\Model;

class Thread extends Model
{
    use RecordsActivity;
    .
    .

    public function hasUpdatesFor($user)
    {
        // Look in the cache for the proper key
        // compare that carbon instance with the $thread->updated_at

        $key = $user->visitedThreadCacheKey($this);

        return $this->updated_at > cache($key);
    }

    public function visits()
    {
        return new Visits($this);
    }
}

我们通过visits()方法声明Visits类,然后记录浏览量和获取浏览量。由于我们使用了不同的方式来记录浏览量,所以我需要修改测试跟记录浏览量等相关逻辑:
forum\tests\Unit\ThreadTest.php

    .
    .
    /** @test */
    public function a_thread_records_each_visit()
    {
        $thread = make('App\Thread',['id' => 1]);

        $thread->visits()->reset();
        $this->assertSame(0,$thread->visits()->count());

        $thread->visits()->record();
        $this->assertEquals(1,$thread->visits()->count());
    }
}

forum\app\Http\Controllers\ThreadsController.php

    .
    .
    public function show($channel,Thread $thread,Trending $trending)
    {
        if(auth()->check()){
            auth()->user()->read($thread);
        }

        $trending->push($thread);

        $thread->visits()->record();

        return view('threads.show',compact('thread'));
    }
    .
    .

forum\resources\views\threads_list.blade.php

        .
        .
        <div class="panel-body">
            <div class="body">{{ $thread->body }}</div>
        </div>

        <div class="panel-footer">
            {{ $thread->visits()->count() }} Visits
        </div>
    </div>
    .
    .

运行测试:
file
页面效果:
file

本文章首发在 LearnKu.com 网站上。

上一篇 下一篇
《L01 基础入门》
我们将带你从零开发一个项目并部署到线上,本课程教授 Web 开发中专业、实用的技能,如 Git 工作流、Laravel Mix 前端工作流等。
《L05 电商实战》
从零开发一个电商项目,功能包括电商后台、商品 & SKU 管理、购物车、订单管理、支付宝支付、微信支付、订单退款流程、优惠券等
讨论数量: 0
发起讨论 查看所有版本


暂无话题~