Menu

68.统计话题浏览量(一)

本节说明

  • 对应视频教程第 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());
    }
}

我们接着新建resetVisitsrecordVisit()$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";
    }
}

运行测试:
file
测试通过,但是我们发现我们新增的 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;
    .
    .

}

再次运行测试:
file
接下来我们在访问话题详情页面时记录浏览量,并在话题列表页面显示出来:
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>
    .
    .

查看效果:
file

本文章首发在 Laravel China 社区
上一篇 下一篇
讨论数量: 0
发起讨论


暂无话题~
刻意练习,每日精进。
0
点赞
65
浏览
0
讨论

维护者