简单的 Record 基类

v0.1.0 2022-09-01 20:49 UTC

This package is auto-updated.

Last update: 2024-09-29 05:50:10 UTC


README

这个库旨在成为创建 PHP 中不可变记录的裸骨库。

示例

use Withinboredom\Record;

class Person extends Record {
    public function __construct(public readonly string $firstName, public readonly string $lastName) {
        // validate here
    }
    
    public function __toString() : string{
        return $this->firstName . ' ' . $this->lastName;
    }
}

$person = new Person('John', 'Doe');
$friend = $person->with(firstName: 'Jane');
echo "$person is friends with $friend";
// output: John Doe is friends with Jane Doe

存在的理由

不可变对象是防止某些类别错误的好方法,随着 PHP 8.1 的推出,我们终于可以将其变为现实。这个库提供了一个非常简单(没有花哨的功能)的方式来复制一个对象,同时使用新的 PHP 语法更改一个或两个参数。唯一缺少的是 IDE 支持... :)

安装

composer require withinboredom/record

运行测试

测试依赖已被故意从 composer.json 文件中省略。

要运行测试,请添加以下内容

{
  "require-dev": {
    "pestphp/pest": "^1.22"
  }
}

然后运行测试

./vendor/bin/pest