laxity7/dto

PHP 通用 DTO 包,易于使用

v1.1.4 2023-08-21 17:44 UTC

This package is auto-updated.

Last update: 2024-09-21 20:25:53 UTC


README

快速轻量级的 Data Transfer Object (DTO) 包,支持嵌套对象和属性变更控制,不检查标量类型,使用 PHP 类型转换进行检查。

License Latest Stable Version Total Downloads

您可以控制 DTO 是否可变,但默认情况下它是不可变的。要使其可变,请使用公共属性或公共设置器。

此包支持 PHP 8.1+

安装

通过 composer 安装

composer require laxity7/dto

如何使用

<?php

use Laxity7\DataTransferObject;

require_once 'vendor/autoload.php';

/**
 * @property-read string $time
 */
class FooDto extends DataTransferObject
{
    public int $id;
    public string $name;
    public array $data; // just array
    /** @var BarDto[] */
    public array $bars; // array of objects BarDto
    public BarDto $bar;
    /** @var BarDto */
    public $baz;
    public BarReadonlyDto $readonlyBar;
    public ReadonlyDto $readonly;
    /** @var ReadonlyDto[] */
    public array $readonlyArr;
    protected string $time;

    // setter can be protected/public
    // setter has higher priority than field
    protected function setName(string $name): void
    {
        $this->name = 'Foo' . $name;
    }

    protected function getTime(): string
    {
        return (new DateTime($this->time))->format('H:i:s');
    }
}

// optional to inherit DataTransferObject
class BarDto
{
    public int $id;
}

// optional to inherit DataTransferObject
class BarReadonlyDto
{
    public function __construct(
        readonly public int $id
    ){}
}

class ReadonlyDto extends DataTransferObject
{
    public function __construct(
        readonly public string $foo,
        readonly public string $bar,
    ) {
        parent::__construct();
    }
}

$fooDto = new FooDto([
    'id' => 1,
    'name' => 'Bar', // FooBar
    'data' => [1, 2, 3],
    'bars' => [ // array of objects
        ['id' => 1], // transforms into an object BarDto
        ['id' => 2], // transforms into an object BarDto
    ],
    'bar' => ['id' => 3], // transforms into an object BarDto
    'baz' => new BarReadonlyDto(4), // just set object
    'readonlyBar' => ['id' => 5], // transforms into an object BarReadonlyDto
    'readonly' => [ // transforms into an object ReadonlyDto
        'bar' => 'baz',
        'foo' => 'gaz',
    ],
    'readonlyArr' => [ // array of objects
        ['bar' => 'baz', 'foo' => 'gaz'], // transforms into an object ReadonlyDto
        ['bar' => 'baz1', 'foo' => 'gaz1'], // transforms into an object ReadonlyDto
    ],
    'time' => '05:59',
]);

// Get all attributes
$arr = $fooDto->toArray();
// Serialize to json (also serializes all nested DTOs)
$json = json_encode($fooDto);