Whip Monstrous Code Into Shape - 04 God Object Cleanup #1: Pass-Through

file

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}();
    }
}
本帖已被设为精华帖!
本帖由系统于 7年前 自动加精
《L05 电商实战》
从零开发一个电商项目,功能包括电商后台、商品 & SKU 管理、购物车、订单管理、支付宝支付、微信支付、订单退款流程、优惠券等
《L04 微信小程序从零到发布》
从小程序个人账户申请开始,带你一步步进行开发一个微信小程序,直到提交微信控制台上线发布。
讨论数量: 5
superwen

道理看明白了,但是数据库结构要调整么?没有交代清楚。

7年前 评论

@superwen 为什么数据库结构要调整,这个主要是讲一些重构代码的思路,肯定不会涉及到数据库结构调整

7年前 评论
superwen

@oustn 细看了一下,明白了,纯粹的代码优化,我以为也附带设计模式上的优化。单独真的创建一个模型。

7年前 评论

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!