takemo101/simple-dto 问题修复 & 功能扩展

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

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

takemo101/simple-dto

最新稳定版本:v0.2.2

Composer 安装命令:

composer require takemo101/simple-dto

包简介

Simple DTO

README 文档

README

Testing PHPStan Validate Composer

The Simple DTO is a library to create simple data objects.
Enjoy!

Installation

Execute the following composer command.

composer require takemo101/simple-dto

Basic usage

Please use as follows

<?php

use Takemo101\SimpleDTO\Attributes\Getter;
use Takemo101\SimpleDTO\Attributes\Ignore;
use Takemo101\SimpleDTO\Attributes\Rename;
use Takemo101\SimpleDTO\Traits\HasSimpleDTO;

class MyDTO
{
    // Use this trait to support arraying and getter methods
    use HasSimpleDTO;

    public function __construct(
        public string $a,
        // Rename array keys
        #[Rename('bb')]
        public string $b,
        // ignore converting to array
        #[Ignore]
        public string $c,
    ) {
        //
    }

    // When set to a getter method, it can be referenced as a property
    #[Getter]
    public function foo(): string
    {
        return 'foo';
    }

    // You can change the name you refer to as a property
    #[Getter('var')]
    public function bar()
    {
        return 'bar';
    }
}

$dto = new MyDTO('a', 'b', 'c');

echo $dto->foo; // foo
echo $dto->var; // bar

// Convert to array
var_dump($dto->toArray()); // ['a' => 'a', 'bb' => 'b', 'foo' => 'foo', 'var' => 'bar']

How to add functionality to convert DTO to array

use Takemo101\SimpleDTO\SimpleDTOFacade;

// A class that implements the DTOTransformer interface can be given as an argument.
// If no arguments are given, the default implementation will be set.
SimpleDTOFacade::setup();

class FirstDTO
{
    use HasSimpleDTO;

    public function __construct(
        public SecondDTO $second,
    ) {
        //
    }
}

class SecondDTO
{
    use HasSimpleDTO;

    public function __construct(
        public string $text,
    ) {
        //
    }
}

$dto = new FirstDTO(new SecondDTO('text'));

// DTO is arrayed by default DTOTransformer.
var_dump($dto->toArray()); // ['second' => ['text' => 'text']]

How to reconstruct a DTO from an array

use Takemo101\SimpleDTO\SimpleDTOFacade;

// omit...

// Reconstructs the DTO from the array, so it can be both arrayed and objectified
$dto = FirstDTO::fromArray(['second' => ['text' => 'text']]);

统计信息

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

GitHub 信息

  • Stars: 2
  • Watchers: 1
  • Forks: 0
  • 开发语言: PHP

其他信息

  • 授权协议: MIT
  • 更新时间: 2022-10-26