oilytortoise/laravel-simple-dto

Laravel 的简单 DTO 包

v1.0.1 2024-09-07 01:05 UTC

This package is auto-updated.

Last update: 2024-09-07 01:32:30 UTC


README

用于在 Laravel 框架中创建简单 DTOs(数据传输对象)的 Composer 包

安装

composer require oilytortoise\laravel-simple-dto

资产

该包包含两个关键类

  • AbstractDto
  • AbstractDtoCollection

用法

DTOs 是一种方便的数据结构,有助于在您的应用程序中发送数据、生成 API 负载/响应、填充传入请求数据等。

虽然所有这些都可以用简单的数组完成,但 DTOs 有额外的优势,可以轻松地将存储的值进行类型转换、自定义填充逻辑,并在必要时添加获取和设置值的函数(然而,通常不建议在 DTO 中包含业务逻辑)。

创建 DTO

创建 DTO 类非常简单。以下是一个示例

<?php

use Oilytortoise\LaravelSimpleDto\AbstractDto;

class UserDto extends AbstractDto
{
   public string $name;
   public ?string $email;
}

就是这样!

您可以按照以下方式创建 DTO 的新实例
$user = new UserDto(['name' => 'Oily Tortoise', 'email' => 'oily@tortoise.com']);

注意:此包目前不支持联合类型属性,例如 public string|int $unionProperty; 将无法工作,我建议暂时不为此属性添加类型提示。我打算很快引入对联合类型支持...

您还可以将其他 DTO 存储为属性

<?php

use Oilytortoise\LaravelSimpleDto\AbstractDto;

class UserConfigDto extends AbstractDto
{
  public string $locale = 'en';
  public bool $2faEnabled = false;
  public bool $subscribedToNewsletter = true;
}

class UserDto extends AbstractDto
{
  public string $name;
  public ?string $email;
  public UserConfigDto $config; // Here, the config property is an instance of the UserConfigDto
}

这些可以通过两种方式构建

  • 通过嵌套数组
$user = new UserDto([
   'name' => 'Oily Tortoise',
   'email' => 'oily@tortoise.com',
   'config' => [
       'locale' => 'en',
       'subscribedToNesletter' => false,
   ]
]);
  • 通过传递一个构建的 DTO
$userConfig = new UserConfigDto();
$user = new UserDto(['name' => 'Oily Tortoise', 'email' => 'oily@tortoise.com', 'config' => $userConfig]);

AbstractDto 构造函数将在构建时递归地构建任何嵌套的 DTOs - 只要传递的值是数组。这非常有帮助,例如,当您生成 API 响应时,您可以创建响应的 DTO 实例来验证返回的数据。只要 DTO 的属性设置正确,它将确保存在所需值。如果缺失,它还将设置默认值。

DTO 集合

基本上是一个 DTOs 集合,可以使用 Laravel 的任何集合函数访问它:[https://laravel.net.cn/docs/11.x/collections#available-methods].

以后再详细说明。

数据库 JSON 转换

许多关系型数据库引擎,如 MySQL,现在支持 JSON 列类型。这些结合 Laravel 的转换功能非常有用。

您可以根据转换指南 [https://laravel.net.cn/docs/11.x/eloquent-mutators#custom-casts] 轻松地将存储在您的表 JSON 列中的数据转换为类型,并创建在检索模型时构建您的 DTO 的转换。

转换的 get()set() 函数通常如下所示(但是您可以根据需要自定义它们)

public function get(Model $model, string $key, mixed $value, array $attributes): mixed
    {
        $dataArray = json_decode($value, true);

        return new UserConfigDto($dataArray);
    }

    public function set(Model $model, string $key, mixed $value, array $attributes): mixed
    {
        $dataArray = $value->toArray();

        return json_encode($dataArray, JSON_UNESCAPED_SLASHES);
    }

Livewire

任何扩展 AbstractDto 的类都自动可用于作为 Livewire 组件属性使用。

这意味着您可以为存储表单值创建 EditUserProfileDto。只要您的组件上有一个公共属性(例如,public EditUserProfileDto $editUserProfileDto;),您就可以在输入元素上使用 wire:model="editUserProfileDto.name"wire:model="editUserProfileDto.email" 等,直接填充 DTO 值。然后您可以使用您喜欢的任何模式验证 DTO 并将数据持久化到数据库中。

更多内容即将到来...