afonsoogomes/laravel-dto

一个用于处理 DTO 的 Laravel 库。

0.0.5 2024-09-27 20:20 UTC

This package is auto-updated.

Last update: 2024-09-27 20:20:51 UTC


README

一个用于创建和管理具有验证和数据传输对象(DTO)的 Artisan 命令的 Laravel 库。

特性

  • DTO 类:用于创建具有验证的 DTO 的基类。
  • Artisan 命令:用于轻松生成新 DTO 类的命令。

安装

要安装此库,请将其添加到您的 composer.json 文件中,或运行以下命令

composer require afonsoogomes/laravel-dto

用法

创建 DTO 类

要创建新的 DTO 类,请使用提供的 Artisan 命令

php artisan make:dto {name}

{name} 替换为您希望 DTO 类的名称。命令将在 app/DTO 目录中生成新的 DTO 类。

示例 DTO 类

以下是使用 DTO 类的示例

namespace App\DTO;

use AfonsoOGomes\LaravelDTO\DTO;

class UserDTO extends DTO
{
    protected function rules(): array
    {
        return [
            'name' => ['required', 'string', 'max:255'],
            'email' => ['required', 'email'],
        ];
    }
}

使用 DTO

您可以创建 DTO 的实例并像这样访问其属性

$userDTO = new UserDTO([
    'name' => 'John Doe',
    'email' => 'john.doe@example.com',
]);

echo $userDTO->name;  // John Doe

高级示例

使用 defaults

defaults 方法允许您为 DTO 字段定义默认值。以下是一个示例

namespace App\DTO;

use AfonsoOGomes\LaravelDTO\DTO;

class ProductDTO extends DTO
{
    protected function rules(): array
    {
        return [
            'name' => ['required', 'string', 'max:255'],
            'price' => ['required', 'numeric'],
            'stock' => ['required', 'integer'],
        ];
    }

    protected function defaults(): array
    {
        return [
            'stock' => 0, // Default stock value
        ];
    }
}

// Using the DTO with default values

$data = [
    'name' => 'Product Name',
    'price' => 19.99,
];

$productDTO = new ProductDTO($data);

echo $productDTO->name;  // Product Name
echo $productDTO->price; // 19.99
echo $productDTO->stock; // 0 (default value)

使用 transform

transform 方法允许您在验证之前处理数据。例如,清理电话号码

namespace App\DTO;

use AfonsoOGomes\LaravelDTO\DTO;

class UserDTO extends DTO
{
    protected function rules(): array
    {
        return [
            'name' => ['required', 'string', 'max:255'],
            'email' => ['required', 'email'],
            'phone' => ['required', 'string', 'size:10'],  // Example: must be 10 digits
        ];
    }

    protected function transform(): array
    {
        return [
            'phone' => preg_replace('/\D/', '', $this->phone) // Remove non-numeric characters from phone
        ];
    }
}

// Using the DTO with data transformation

$data = [
    'name' => 'John Doe',
    'email' => 'john.doe@example.com',
    'phone' => '(123) 456-7890', // Original format
];

$userDTO = new UserDTO($data);

echo $userDTO->name;   // John Doe
echo $userDTO->email;  // john.doe@example.com
echo $userDTO->phone;  // 1234567890 (transformed to 10 digits)

组合示例

以下是一个同时使用 defaultstransform 的示例

namespace App\DTO;

use AfonsoOGomes\LaravelDTO\DTO;

class OrderDTO extends DTO
{
    protected function rules(): array
    {
        return [
            'order_id' => ['required', 'string'],
            'amount' => ['required', 'numeric'],
            'currency' => ['required', 'string', 'size:3'], // Example: 3-letter currency code
        ];
    }

    protected function defaults(): array
    {
        return [
            'currency' => 'USD', // Default currency value
        ];
    }

    protected function transform(): array
    {
        return [
            'order_id' => strtoupper($this->order_id), // Transform order ID to uppercase
        ];
    }
}

// Using the DTO with default values and data transformation

$data = [
    'order_id' => 'abc123',
    'amount' => 99.99,
];

$orderDTO = new OrderDTO($data);

echo $orderDTO->order_id; // ABC123 (transformed to uppercase)
echo $orderDTO->amount;   // 99.99
echo $orderDTO->currency; // USD (default value)

命令选项

  • name:要创建的 DTO 类的名称。您可以使用斜杠创建嵌套目录。

示例

php artisan make:dto UserProfileDTO

这将创建一个位于 app/DTO 目录中的 UserProfileDTO.php 文件。

配置

DTO 构造函数

DTO 构造函数接受以下参数

  • array $items:DTO 的初始数据。

方法

  • __construct(array $items = []):构造函数,用于使用数据初始化 DTO 并执行验证。
  • rules():方法,用于定义 DTO 的验证规则。在您的 DTO 类中重写此方法。
  • transform():方法,用于在验证之前预处理数据。
  • defaults():方法,用于定义 DTO 的默认值。
  • get($key, $default = null):方法,用于通过键从 DTO 获取值。
  • all():方法,用于获取 DTO 中的所有数据。
  • has($key):方法,用于检查键是否存在于 DTO 中。
  • set(string $key, $value):方法,用于通过键在 DTO 中设置值。
  • remove(string $key):方法,用于通过键从 DTO 中删除值。
  • count():方法,用于计算 DTO 中的项目数量。
  • toArray():方法,用于将 DTO 转换为数组。
  • toJson():方法,用于将 DTO 转换为 JSON 字符串。
  • fromJson(string $json):静态方法,用于从 JSON 字符串创建新的 DTO 实例。
  • fromArray(array $data):静态方法,用于从数组创建新的 DTO 实例。

测试

要测试此库,请确保您已安装并配置了 Laravel。使用 Artisan 命令创建一个新的 DTO 类,并验证它是否按预期工作。

贡献

如果您想为此库做出贡献,请在 GitHub 上提交拉取请求。确保您遵循编码标准,并为新功能包含测试。

许可证

此库采用 MIT 许可证。有关更多信息,请参阅 LICENSE 文件。