承接 jnariai/simple-dto 相关项目开发

从需求分析到上线部署,全程专人跟进,保证项目质量与交付效率

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

jnariai/simple-dto

最新稳定版本:1.0.0

Composer 安装命令:

composer require jnariai/simple-dto

包简介

A simple data transfer object for Laravel

README 文档

README

Immutable Data Transfer Object (DTO) for PHP inspired by Laravel Data and Bags

Introduction

This is a package to create minimal immutable Data Transfer Object for PHP with some handy features like the method from to create the dto from array, it implements Arrayable and Jsonable interfaces, and also has two attributes to use #[NonNullOutput] and #[Hidden] to help in the output transformation.

Installation

You can install the package via composer:

composer require jnariai/simple-dto

Usage

use SimpleDTO\DTO;

final readonly class MyDTO extends DTO
{
    public function __construct(
        public bool $property_bool,
        public ?string $property_string,
        public string $sensitive_data,
    ) {}
}

You can create the DTO using the static function from:: and pass an array of data

$myDTO = MyDTO::from([
    'property_bool' => true,
    'sensitive_data' => 'sensitive data',
]);

// You don't need to pass properties that can be null, it will automatically be set to null
/* MyDTO {
  +property_bool: true
  +property_string: null
  +sensitive_data: "sensitive data"
}
*/ 

You can also get a toArray an toJson method

$myDTO->toArray(); // ['property_bool' => true, 'property_string' => null, 'sensitive_data' => 'sensitive data']
$myDTO->toJson(); // {"property_bool":true,"property_string":null,"sensitive_data":"sensitive data"}

You also get two available attributes to use. #[NonNullOutput] and #[Hidden].

#[NonNullOutput] is a class Attribute and when using toArray or toJson it will only return properties that are not null.

use SimpleDTO\DTO;

#[NonNullOutput]
final readonly class MyDTO extends DTO
{
    public function __construct(
        public bool $property_bool,
        public ?string $property_string,
        public string $sensitive_data,
    ) {}
}

$myDTO->toArray(); // ['property_bool' => true, 'sensitive_data' => 'sensitive data']
$myDTO->toJson(); // {"property_bool":true,"sensitive_data":"sensitive data"}

#[Hidden] is a property Attribute and when using toArray or toJson it will not return the property.

use SimpleDTO\DTO;

final readonly class MyDTO extends DTO
{
    public function __construct(
    public bool $property_bool,
    public ?string $property_string,
    #[Hidden]
    public string $sensitive_data,
    ) {}
}

$myDTO->toArray(); // ['property_bool' => true, 'property_string' => null]
$myDTO->toJson(); // {"property_bool":true,"property_string":null}

License

The MIT License (MIT). Please see License File for more information.

统计信息

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

GitHub 信息

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

其他信息

  • 授权协议: MIT
  • 更新时间: 2025-03-09