69.统计话题浏览量(二)
- 本系列文章为
laracasts.com
的系列视频教程——Let's Build A Forum with Laravel and TDD 的学习笔记。若喜欢该系列视频,可去该网站订阅后下载该系列视频, 支持正版 ;- 视频源码地址:github.com/laracasts/Lets-Build-a-...;
- 本项目为一个 forum(论坛)项目,与本站的第二本实战教程 《Laravel 教程 - Web 开发实战进阶》 类似,可互相参照。
本节说明
- 对应视频教程第 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>
.
.
运行测试:
页面效果: