owlnext-fr/dto-export

Symfony + API Platform 的供应商,用于将 API DTOs 导出为其他语言,以便前端易于集成。

1.0.2 2023-10-18 20:55 UTC

This package is auto-updated.

Last update: 2024-09-18 23:16:35 UTC


README

Symfony + API Platform 的供应商,用于将 API DTOs 导出为其他语言,以便前端易于集成。

安装

1. 安装包

composer require owlnext-fr/dto-export

2. 配置 twig 路径

# config/packages/twig.yaml
twig:
  #...
  paths:
    '%kernel.project_dir%/vendor/owlnext-fr/dto-export/templates': 'owlnext_fr.dto_export'

用法

1. 创建 DTO 类

# src/Dto/Output/UserOutputDTO.php
<?php

namespace App\Dto\Output;

class UserOutputDTO {
    public int $id;
    public string $name;
}

2. 在你的类中添加标签 app.exportable_dto

使用注解

# src/Dto/Output/UserOutputDTO.php

use Symfony\Component\DependencyInjection\Attribute\AutoconfigureTag;

#[AutoconfigureTag('app.exportable_dto')]
class UserOutputDTO {
    public int $id;
    public string $name;
}

使用接口实现

为了避免在每个 DTO 中使用 AutoconfigureTag 注解,你可以创建一个 ExportableDTOInterface 接口,并在你的 DTO 中实现它。

# src/Dto/Impl/ExportableDTOInterface.php

namespace App\Dto\Impl;

use Symfony\Component\DependencyInjection\Attribute\AutoconfigureTag;

#[AutoconfigureTag('app.exportable_dto')]
interface ExportableDTOInterface {}
# src/Dto/Output/UserOutputDTO.php

use App\Dto\Impl\ExportableDTOInterface;

class UserOutputDTO implements ExportableDTOInterface {
    public int $id;
    public string $name;
}

处理某种东西的数组

对于原始数据、标量和对象的数组,你需要在你的字段中添加另一个属性,使用数组。这将帮助导出器了解数组中的数据类型,并正确地转换它。

以下是一个字符串数组的示例

# src/Dto/Output/UserOutputDTO.php

# ...
use OwlnextFr\DtoExport\Attribute\ListOf;

class UserOutputDTO implements ExportableDTOInterface {
    #...
    
    #[ListOf(type: 'string')]
    /** @var string[] $roles list roles for this user. */
    public array $roles;
}

以下是一个对象数组的示例

# src/Dto/Output/UserOutputDTO.php

# ...
use OwlnextFr\DtoExport\Attribute\ListOf;
use App\DTO\Output\SkillOutputDTO;

class UserOutputDTO implements ExportableDTOInterface {
    #...
    
    #[ListOf(type: SkillOutputDTO::class)]
    /** @var SkillOutputDTO[] $roles list skills of this user. */
    public array $skills;
}

3. 导出你的 DTOs

基本用法

symfony console dto:export ...

对于 dart 语言

symfony console dto:export <path to export> --type=dart --project-name=<project name>

对于 TypeScript 语言

symfony console dto:export <path to export> --type=typescript