zendrop/data

此包允许您轻松创建数据传输对象

v2.0.4 2024-09-20 12:52 UTC

README

安装

要通过Composer安装此包,请运行以下命令

composer require zendrop/data

使用方法

创建数据模型

  1. 实现接口:您的模型应实现 DataInterfaceToArrayInterface
  2. 使用特质:为了功能,结合使用 DataTraitToArrayTrait
  3. 处理数组:为了验证数组,使用 ArrayOf 属性。用 Skippable 标记可以跳过的字段。
  4. 嵌套结构:您可以在模型内创建模型。
  5. 枚举:对于枚举类型,使用 BackedEnum。

代码示例

<?php

use Zendrop\Data\DataInterface;
use Zendrop\Data\DataTrait;
use Zendrop\Data\Attributes\ArrayOf;
use Zendrop\Data\Skippable;
use Zendrop\Data\ToArrayInterface;
use Zendrop\Data\ToArrayTrait;

class Tag implements DataInterface, ToArrayInterface
{
    use DataTrait;
    use ToArrayTrait;

    public function __construct(
        public readonly string $name
    ) {
    }
}

enum Occupation: string
{
    case Manager: 'manager';
    case Developer: 'developer';
}

class User implements DataInterface, ToArrayInterface
{
    use DataTrait;
    use ToArrayTrait;

    public function __construct(
        public readonly int $id,
        
        public readonly string $userName,
        
        /** @var Tag[] */
        #[ArrayOf(Tag::class)]
        public readonly array $tags,
        
        public readonly Occupation $occupation,
        
        public readonly string|Skippable $bio = Skippable::Skipped
    ) {
    }
}

实例化和序列化

使用自动类型转换和键规范化从数组创建对象。使用灵活的键格式将对象序列化回数组。

// Create a User object from an array
$user = User::from([
    'id' => '42',                // will be converted to int
    'user_name' => 'John Doe',
    'tags' => [
        ['name' => 'friend'],    // will be converted to Tag class
        ['name' => 'zendrop']
    ],
    'occupation' => 'developer'  // will be converted to Occupation enum
    // 'bio' is optional and skipped here
]);

// Serialize the User object to an array
$arraySnakeCase = $user->toArray(); // Default snake_case
$arrayCamelCase = $user->toArray(ToArrayCase::Camel);
$arrayKebabCase = $user->toArray(ToArrayCase::Kebab);