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

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

上一篇 下一篇
《L05 电商实战》
从零开发一个电商项目,功能包括电商后台、商品 & SKU 管理、购物车、订单管理、支付宝支付、微信支付、订单退款流程、优惠券等
《G01 Go 实战入门》
从零开始带你一步步开发一个 Go 博客项目,让你在最短的时间内学会使用 Go 进行编码。项目结构很大程度上参考了 Laravel。
讨论数量: 0
发起讨论 只看当前版本


暂无话题~