70.统计话题浏览量(三)
- 本系列文章为
laracasts.com
的系列视频教程 ——Let's Build A Forum with Laravel and TDD 的学习笔记。若喜欢该系列视频,可去该网站订阅后下载该系列视频, 支持正版 ;- 视频源码地址:github.com/laracasts/Lets-Build-a-...;
- 本项目为一个 forum(论坛)项目,与本站的第二本实战教程 《Laravel 教程 - Web 开发实战进阶》 类似,可互相参照。
本节说明#
- 对应视频教程第 70 小节:Thread Views: Design #3 - KISS
本节内容#
本节我们使用第三种方式来实现话题浏览量的统计功能。本节我们将会应用 KISS 原则:
KISS 原则是英语 Keep It Simple, Stupid 的首字母缩略字,是一种归纳过的经验原则。KISS 原则是指在设计当中应当注重简约的原则。总结工程専业人员在设计过程中的经验,大多数系统的设计应保持简洁和单纯,而不掺入非必要的复杂性,这样的系统运作成效会取得最优;因此简单性应该是设计中的关键目标,尽量回避免不必要的复杂性。
第一种、第二种方式中,我们都使用到了 Redis。因为我们假设的是,当前我们的应用十分流行,有很多很多的人访问。为了减小数据库的压力,我们使用了 Redis 缓存。但是,清醒下吧,我们的应用没啥人用,就咱自己鼓捣下,所以,我们就得 Keep It Simple, Stupid。首先我们删除 Visits
类文件、a_thread_records_each_visit
测试以及 visits()
方法,然后我们再新建一个测试:
forum\tests\Feature\ReadThreadsTest.php
.
.
/** @test */
public function we_record_a_new_visit_each_time_the_thread_is_read()
{
$thread = create('App\Thread');
$this->assertSame(0,$thread->visits);
}
}
我们需要给 threads
表增加一列:visits
,用来记录话题浏览量。我们来修改迁移文件:
forum\database\migrations{timestamp}_create_threads_table.php
.
.
public function up()
{
Schema::create('threads', function (Blueprint $table) {
$table->increments('id');
$table->unsignedInteger('user_id');
$table->unsignedInteger('channel_id');
$table->unsignedInteger('replies_count')->default(0);
$table->unsignedInteger('visits')->default(0);
$table->string('title');
$table->text('body');
$table->timestamps();
});
}.
.
运行迁移:
$ php artisan migrate:refresh
进入 Tinker
:
$ php artisan tinker
填充数据:
>>> factory('App\Thread',30)->create();
我们运行测试:
测试未通过,我们 dd($thread->toArray())
:
因为我们没有给 visits
属性赋值,所以 visits
没有绑定到模型的属性组中。现在我们有两个方案可以解决这个问题,第一种是利用 fresh()
方法:
$this->assertEquals(0,$thread->fresh()->visits);
第二种是修改模型工厂文件,直接为模型的 visits
属性返回 0:
forum\database\factories\ModelFactory.php
.
.
$factory->define(App\Thread::class,function ($faker){
return [
'user_id' => function () {
return factory('App\User')->create()->id;
},
'channel_id' => function () {
return factory('App\Channel')->create()->id;
},
'title' => $faker->sentence,
'body' => $faker->paragraph,
'visits' => 0
];
});
.
.
那么我们的测试就可以写作:
$this->assertSame(0,$thread->visits);
运行测试:
接下来我们完善测试:
forum\tests\Feature\ReadThreadsTest.php
.
.
/** @test */
public function we_record_a_new_visit_each_time_the_thread_is_read()
{
$thread = create('App\Thread');
$this->assertSame(0,$thread->visits);
$this->call('GET',$thread->path());
$this->assertEquals(1,$thread->fresh()->visits);
}
}
修改控制器:
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->increment('visits');
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>
.
.
页面效果:
最后地最后,让我们来运行一下全部的测试:
推荐文章: