moonspot/value-objects

用于创建易于在 JSON APIs 中处理的值对象的基类

v2.1.0 2024-03-01 20:10 UTC

This package is auto-updated.

Last update: 2024-08-30 21:10:23 UTC


README

这个库提供了一个创建值对象的基类,这些值对象可以轻松地从 YAML 和 JSON 创建,并用于创建 API 端点。

\Moonspot\ValueObjects\ValueObject

这个类提供了将数组、JSON 和 YAML 转换为对象的方法,并将它们导出回这些形式。

<?php

namespace Example;

use Moonspot\ValueObjects\ValueObject;

class Car extends ValueObject {

    public int $id = 0;

    public string $model = '';

    public string $make = '';


}

$car = new Car();
$car->fromArray(
    [
        'id'    => 1,
        'model' => 'Kia',
        'make'  => 'Sportage'
    ]
);

echo $car->toJSON();
{
    "id":    1,
    "model": "Kia",
    "make":  "Sportage"
}

\Moonspot\ValueObjects\TypedArray

这是一个用于创建需要添加特定类型或类型到 ArrayObject 的 ArrayObject 的基类。此外,该类将提供导出接口。此外,内部数组中的任何对象都将进行深度导出。

<?php

namespace Example;

use Moonspot\ValueObjects\TypedArray;
use Moonspot\ValueObjects\ValueObject;

class CarSet extends TypedArray {
    public const REQUIRED_TYPE = [Car::class];
}

class Fleet extends ValueObject {
    public int $id = 0;

    public string $name = '';

    public CarSet $cars;

    public function __construct() {
        // Any properties which are ValueObjects or TypedArrays should be
        // initialized in the ValueObject's constructor
        $this->cars = new CarSet();
    }
}

$car = new Car();
$car->fromArray(
    [
        'id'    => 1,
        'model' => 'Kia',
        'make'  => 'Sportage'
    ]
);

$fleet = new Fleet();
$fleet->id = 1;
$fleet->name = "New Fleet";
$fleet->cars[] = $car;

echo $fleet->toJSON();
{
    "id": 1,
    "name": "New Fleet",
    "cars": [
        {
            "id":    1,
            "model": "Kia",
            "make":  "Sportage"
        }
    ]
}

\Moonspot\ValueObjects\ArrayObject

这是 TypedArray 的基类,并扩展了原生的 ArrayObject 类,添加了导出接口的方法。当需要将非结构化数组数据作为值对象的一部分时,这很有用。

<?php

namespace Example;

use Moonspot\ValueObjects\ValueObject;
use Moonspot\ValueObjects\ArrayObject;

class Car extends ValueObject {

    public int $id = 0;

    public string $model = '';

    public string $make = '';

    public ArrayObject $attributes;

    public function __construct() {
        // Any properties which are ValueObjects or TypedArrays should be
        // initialized in the ValueObject's constructor
        $this->attributes = new ArrayObject();
    }
}

$car        = new Car();
$car->id    = 1;
$car->model = 'Kia';
$car->make  = 'Sportage';

$car->attributes['color'] = 'Blue';
$car->attributes['passengers'] = 5;
echo $car->toJSON();
{
    "id":    1,
    "model": "Kia",
    "make":  "Sportage",
    "attributes": {
        "color": "Blue",
        "passengers": 5
    }
}