PHP 技巧 - 封装基本的数据类型

对于一些基本数据类型 intstringbool 等,可以根据以下几个规则来判断是否要对其进行封装。

封装是否让信息更加的清晰 ?

示例

cache([], 50)

在该例子中,我们无法一眼就明确 50 代表的是秒、分钟还是其他单位时间,因此,可以对其进行封装

class Second {
    protected $seconds;
    public function __construct($seconds)
    {
        $this->seconds = $seconds;
    }
}

封装后要表达的信息将变得更加明确

function cache($data, Second $second)
{

}
cache([], new Second(50));

是否存在与属性相关联的行为 ?

例如,对于 weight(体重) 属性而言,有着相关联的行为,比如 gain(增加), gain 会导致 weight 的增加。通过封装可以将属性和行为进行关联。

class Weight {
    protected $weight;
    public function __construct($weight)
    {
        $this->weight = $weight;
    }
    public function gain($pounds)
    {
        $this->weight += $pounds;
    }
    public function lose($pounds)
    {
        $this->weight -= $pounds;
    }
}

是否存在与属性相关的验证,来保持属性的一致性 ?

将属性进行封装,可以对属性的类型进行验证,保持属性的一致性。例如,邮箱地址这一属性需要验证邮箱的合法性

class EmailAddress {
    public function __construct($email)
    {
        if(! filter_var($email, FILTER_VALIDATE_EMAIL)){
            throw new InvalidArgumentException;
        }

        $this->email = $email;
    }
}

是否为重要的领域概念 ?

当属性体现出具体的业务需求时,可以将其进行封装。

class Location {
    public function __construct($latitude, $longtitude)
    {

    }
}

完整示例 - 健身相关业务封装

体重

class Weight {
    protected $weight;
    public function __construct($weight)
    {
        $this->weight = $weight;
    }
    public function gain($pounds)
    {
        $this->weight += $pounds;
    }
    public function lose($pounds)
    {
        $this->weight -= $pounds;
    }
}

锻炼时长

class Timelength {
    protected $seconds;
    public function __construct($seconds)
    {
        $this->seconds = $seconds;
    }
    public static function fromMinutes($minutes)
    {
        return new static($minutes * 60);
    }
    public static function fromHours($hours)
    {
        return new static($hours * 60 * 60);
    }
    public function fromSeconds()
    {
        return $this->seconds;
    }
}

会员

class WorkoutPlaceMember {
    public function __construct($name, Weight $weight)
    {

    }
    public function workoutFor(Timelenght $lenght)
    {

    }
    public function workoutForHours($hour)
    {

    }
}

新增会员,录入体重

$joe = new WorkoutPlaceMember('joe', new Weight(165));

记录会员的锻炼时长

$joe->workoutFor(new Timelength(30));
$joe->workoutFor(Timelength::fromMinutes(34));

参考:

本作品采用《CC 协议》,转载必须注明作者和本文链接
本帖由系统于 3年前 自动加精
讨论数量: 1

不错,挺好的

3年前 评论

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