Whip Monstrous Code Into Shape - 04 God Object Cleanup #1: Pass-Through
Any developer who has worked on the same project for a year or more will be well aware of the fact that, if you're not careful, your User class can quickly turn into a monstrous God object. In the next few videos, one tip at a time, we'll review techniques you might implement to clean things up.
In this first example, we'll recognize related methods, and extract them to a dedicated object - which we then pass through to from our main User class.
之前三个视频讲的都是如何更好的维护控制器的简洁有序,接下来这3个视频主要讲的是如何清理模型,标题我也不知道怎么翻译好,大家理解就行。
随着时间的过去,项目体积也不停的递增,相应的你的模型也越来越臃肿,首当其冲的就是 User 模型了。打个比方,一个简单的博客系统,就像 laravel-china
一样吧,一个用户有话题、评论数和话题,通常我们会写在模型中(不过laravel-china
好像会更新到数据库中?打个比方..):
public function commentsCount()
{
return $this->comments->count();
}
public function topicsCount()
{
return $this->topics->count();
}
public function favoritesCount()
{
return $this->favorites->count();
}
然后可以很简单的通过 $user->favoritesCount()
的方式访问。
视频中给出了一个方法,因为这三个属性都是代表用户的一个状态,所以可以通过添加一个 state 类来把这三个状态封装起来。用户模型添加一个 state 方法:
public function state()
{
return new UserState($this);
}
然后把这三个方法移到 UserState 类中:
class UserState
{
/**
* @var User
*/
private $user;
/**
* UserState constructor.
* @param User $this
*/
public function __construct(User $user)
{
$this->user = $user;
}
public function comments()
{
return $this->user->comments->count();
}
public function topics()
{
return $this->user->topics->count();
}
public function favorites()
{
return $this->user->favorites->count();
}
}
然后就是通过 $user->state()->favorites()
访问了。你也可以加个 __get 魔术方法,看起来就像是调用属性:$user->state()->favorites
。
public function __get($attribute)
{
if (method_exists($this, $attribute)){
return $this->{$attribute}();
}
}
推荐文章: