不可变普通PHP对象

dev-master 2019-02-27 21:00 UTC

This package is auto-updated.

Last update: 2024-09-04 08:24:46 UTC


README

  • 不可变 - 使用 with 而不是设置器
  • 静态类型 - 您的工具喜欢它
  • 可克隆 - 没有引用共享
  • 可序列化 - 到JSON,到数组和到字符串

— 自动生成的普通PHP对象。

🛡️ 两个库的源代码及其生成的代码都可以通过 Phan 在其最严格的级别上进行验证。

使用方法

定义文件看起来像

namespace: App

definitions:
  - User:
    id: int
    name: string
    email: string
    isAdmin: [bool, 'false']
    birthDate: [?\DateTime, 'null']

不言自明,它声明了一个位于 App 命名空间中的 User 类,具有 member: typemember: [type, default]。就是这样简单。

您被鼓励将其作为项目的开发依赖项安装

$ composer install --dev leocavalcante/ippo dev-master

它将在 vendor/bin 中放置一个二进制文件,该文件仅需要两个参数:定义文件和输出目录。

$ vendor/bin/ippo definitions.yml src/generated/

输出示例

从上面的定义中,您得到一个 User

class User implements \JsonSerializable

具有如下构造函数

public function __construct(
    int $id,
    string $name,
    string $email,
    bool $isAdmin = false,
    ?\DateTime $birthDate = null
) {
    $this->id = $id;
    $this->name = $name;
    $this->email = $email;
    $this->isAdmin = $isAdmin;
    $this->birthDate = $birthDate;
}

每个声明的属性都有获取器和 withs,例如

public function getName(): string
{
    return $this->name;
}

public function withName(string $name): User
{
    return new User(
        $this->id,
        $name,
        $this->email,
        $this->isAdmin,
        $this->birthDate
    );
}

以及序列化方法如 toArray

public function toArray(): array
{
    return [
        'id' => $this->id,
        'name' => $this->name,
        'email' => $this->email,
        'is_admin' => $this->isAdmin,
        'birth_date' => $this->birthDate,
    ];
}

toString()

public function toString()
{
    $id = json_encode($this->id);
    $name = json_encode($this->name);
    $email = json_encode($this->email);
    $isAdmin = json_encode($this->isAdmin);
    $birthDate = json_encode($this->birthDate);

    return "User(\n\tid => {$id};\n\tname => {$name};\n\temail => {$email};\n\tisAdmin => {$isAdmin};\n\tbirthDate => {$birthDate};\n)";
}

方便的工厂方法,如 fromArrayfromJson

static public function fromArray(array $source): User
{
    return new User(
        $source['id'] ?? null,
        $source['name'] ?? null,
        $source['email'] ?? null,
        $source['is_admin'] ?? false,
        $source['birth_date'] ?? null,
    );
}

static public function fromJson(string $json): User
{
    $source = json_decode($json, true);

    if (false === $source) {
        throw new \InvalidArgumentException('JSON decode error: '.json_last_error_msg());
    }

    if (!is_array($source)) {
        throw new \InvalidArgumentException('Your JSON didnt decoded to an array');
    }

    return User::fromArray($source);
}

在此处查看完整的输出