68.统计话题浏览量(一)
- 本系列文章为
laracasts.com
的系列视频教程 ——Let's Build A Forum with Laravel and TDD 的学习笔记。若喜欢该系列视频,可去该网站订阅后下载该系列视频, 支持正版 ;- 视频源码地址:github.com/laracasts/Lets-Build-a-...;
- 本项目为一个 forum(论坛)项目,与本站的第二本实战教程 《Laravel 教程 - Web 开发实战进阶》 类似,可互相参照。
本节说明#
- 对应视频教程第 68 小节:Thread Views: Design #1 - Trait
本节内容#
我们下一个功能是统计话题的浏览量。接下来的三节我们将使用三种不同的方式来实现功能,本节我们使用 Trait
来实现。按照惯例,我们先建立测试:
forum\tests\Unit\ThreadTest.php
.
.
/** @test */
public function a_thread_records_each_visit()
{
$thread = make('App\Thread',['id' => 1]);
$thread->resetVisits();
$this->assertSame(0,$thread->visits());
$thread->recordVisit();
$this->assertEquals(1,$thread->visits());
$thread->recordVisit();
$this->assertEquals(2,$thread->visits());
}
}
我们接着新建 resetVisits
、recordVisit()
、$thread->visits()
方法:
forum\app\Thread.php
.
.
public function recordVisit()
{
Redis::incr($this->visitsCacheKey());
return $this;
}
public function visits()
{
return Redis::get($this->visitsCacheKey()) ?: 0;
}
public function resetVisits()
{
Redis::del($this->visitsCacheKey());
return $this;
}
public function visitsCacheKey()
{
return "threads.{$this->id}.visits";
}
}
运行测试:
测试通过,但是我们发现我们新增的 4 个方法跟 Thread
模型并无太大关联,所以我们将以上 4 个方法抽取到 Trait
中:
forum\app\RecordsVisits.php
<?php
namespace App;
use Illuminate\Support\Facades\Redis;
trait RecordsVisits
{
public function recordVisit()
{
Redis::incr($this->visitsCacheKey());
return $this;
}
public function visits()
{
return Redis::get($this->visitsCacheKey()) ?: 0;
}
public function resetVisits()
{
Redis::del($this->visitsCacheKey());
return $this;
}
public function visitsCacheKey()
{
return "threads.{$this->id}.visits";
}
}
接下来我们只用在 Thread
模型文件中引用 Trait
即可:
<?php
namespace App;
use App\Events\ThreadReceivedNewReply;
use Illuminate\Database\Eloquent\Model;
class Thread extends Model
{
use RecordsActivity,RecordsVisits;
.
.
}
再次运行测试:
接下来我们在访问话题详情页面时记录浏览量,并在话题列表页面显示出来:
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->recordVisit();
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() }} Visits
</div>
</div>
.
.
查看效果:
推荐文章: