59.为被 @ 的用户名加上链接
- 本系列文章为
laracasts.com
的系列视频教程 ——Let's Build A Forum with Laravel and TDD 的学习笔记。若喜欢该系列视频,可去该网站订阅后下载该系列视频, 支持正版 ;- 视频源码地址:github.com/laracasts/Lets-Build-a-...;
- 本项目为一个 forum(论坛)项目,与本站的第二本实战教程 《Laravel 教程 - Web 开发实战进阶》 类似,可互相参照。
本节说明#
- 对应视频教程第 59 小节:Wrap Usernames Within Anchor Tags
本节内容#
本节我们为被 @ 的用户名加上链接,点击可以跳转到该用户的个人页面。首先依旧是新建测试:
forum\tests\Unit\ReplyTest.php
.
.
/** @test */
public function it_warps_mentioned_usernames_in_the_body_within_archor_tags()
{
$reply = create('App\Reply',[
'body' => 'Hello @Jane-Doe.'
]);
$this->assertEquals(
'Hello <a href="/profiles/Jane-Doe">@Jane-Doe</a>.',
$reply->body
);
}
}
我们利用 修改器来修改 body
属性的值:
forum\app\Reply.php
.
.
public function setBodyAttribute($body)
{
$this->attributes['body'] = preg_replace('/@([\w\-]+)/','<a href="/profiles/$1">$0</a>',$body);
}
}
注意我们使用了不同的正则表达式,我们待会儿会谈到这个问题
运行测试:
运行全部测试:
有两个测试未通过,这是因为现在我们回复的内容中的用户名会被 a
标签包裹,所以需要更新我们的正则表达式:
forum\app\Reply.php
.
.
public function mentionedUsers()
{
preg_match_all('/@([\w\-]+)/',$this->body,$matches);
return $matches[1];
}
.
.
再次运行测试:
推荐文章: