zendrop/data 问题修复 & 功能扩展

解决BUG、新增功能、兼容多环境部署,快速响应你的开发需求

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

zendrop/data

最新稳定版本:v2.0.5

Composer 安装命令:

composer require zendrop/data

包简介

This package allows you to created DataTransferObjects without pain

README 文档

README

Installation

To install the package via Composer, run the following command:

composer require zendrop/data

How To Use

Creating Data Models

  1. Implement Interfaces: Your models should implement DataInterface and ToArrayInterface.
  2. Use Traits: Incorporate DataTrait and ToArrayTrait for functionality.
  3. Handle Arrays: For validating arrays, use the ArrayOf attribute. Mark fields that can be skipped with Skippable.
  4. Nested Structures: You can create models within models.
  5. Enums: Use BackedEnum for enum types.

Code Example

<?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
    ) {
    }
}

Instantiation and Serialization

Create objects from arrays with automatic type conversion and key normalization. Serialize objects back to arrays with flexible key formatting.

// 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);

统计信息

  • 总下载量: 95.35k
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 3
  • 点击次数: 1
  • 依赖项目数: 2
  • 推荐数: 0

GitHub 信息

  • Stars: 3
  • Watchers: 5
  • Forks: 0
  • 开发语言: PHP

其他信息

  • 授权协议: MIT
  • 更新时间: 2024-02-19