84.锁定话题(一)
- 本系列文章为
laracasts.com
的系列视频教程——Let's Build A Forum with Laravel and TDD 的学习笔记。若喜欢该系列视频,可去该网站订阅后下载该系列视频, 支持正版 ;- 视频源码地址:github.com/laracasts/Lets-Build-a-...;
- 本项目为一个 forum(论坛)项目,与本站的第二本实战教程 《Laravel 教程 - Web 开发实战进阶》 类似,可互相参照。
本节说明
- 对应视频教程第 84 小节:An Administrator May Lock Any Thread
本节内容
本节我们开始锁定话题功能的开发。如果管理员锁定了某一话题,那么该话题将不能进行回复。首先新建测试:
forum\tests\Unit\ThreadTest.php
.
.
/** @test */
public function a_thread_can_be_locked()
{
$this->assertFalse($this->thread->locked);
$this->thread->lock();
$this->assertTrue($this->thread->locked);
}
}
接着我们修改迁移文件,添加locked
字段:
forum\database\migrations{timestamp}_create_threads_table.php
.
.
public function up()
{
Schema::create('threads', function (Blueprint $table) {
$table->increments('id');
$table->string('slug')->unique()->nullable();
$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->unsignedInteger('best_reply_id')->nullable();
$table->boolean('locked')->default(false);
$table->timestamps();
});
}
.
.
为了方便测试,我们修改下模型工厂文件:
forum\database\factories\ModelFactory.php
.
.
$factory->define(App\Thread::class,function ($faker){
$title = $faker->sentence;
return [
'user_id' => function () {
return factory('App\User')->create()->id;
},
'channel_id' => function () {
return factory('App\Channel')->create()->id;
},
'title' => $title,
'body' => $faker->paragraph,
'visits' => 0,
'slug' => str_slug($title),
'locked' => false
];
});
.
.
然后我们添加lock()
方法:
forum\app\Thread.php
.
.
public function addReply($reply)
{
$reply = $this->replies()->create($reply);
event(new ThreadReceivedNewReply($reply));
return $reply;
}
public function lock()
{
$this->update(['locked' => true]);
}
.
.
运行测试:
接下来我们为锁定话题功能新建一个测试文件,并添加第一个功能测试:
forum\tests\Feature\LockThreadsTest.php
<?php
namespace Tests\Feature;
use Tests\TestCase;
use Illuminate\Foundation\Testing\DatabaseMigrations;
class LockThreadsTest extends TestCase
{
use DatabaseMigrations;
/** @test */
public function once_locked_thread_may_not_receive_new_replies()
{
$this->signIn();
$thread = create('App\Thread');
$thread->lock();
$this->post($thread->path() . '/replies',[
'body' => 'Foobar',
'user_id' => auth()->id()
])->assertStatus(422);
}
}
运行测试:
因为我们没有对锁定话题发布评论的动作做限制,我们来加上限制:
forum\app\Http\Controllers\RepliesController.php
.
.
public function store($channelId, Thread $thread, CreatePostRequest $form)
{
if($thread->locked) {
return response('Thread is locked.',422);
}
return $thread->addReply([
'body' => request('body'),
'user_id' => auth()->id(),
])->load('owner');
}
.
.
再次运行测试:
推荐文章: