skrepr/id-type

Symfony 扩展包,用于生成和验证 ID 类型

维护者

详细信息

github.com/skrepr/id-type

源代码

问题

安装次数: 1,520

依赖项: 0

建议者: 0

安全性: 0

星标: 3

关注者: 3

分支: 0

公开问题: 0

类型:symfony-bundle

1.3.1 2024-09-24 07:26 UTC

This package is auto-updated.

Last update: 2024-09-24 07:27:22 UTC


README

skrepr_logo

Skrepr ID 类型

Releases LICENSE Issues Stars

Symfony 扩展包,用于生成和验证 ID 类型

先决条件

此版本的项目需要

  • PHP 8.3+
  • Symfony 6.4+

安装

您可以通过 composer 安装库

composer require skrepr/id-type

该扩展包应该由 symfony/flex 启用,如果不启用

// config/bundles.php

<?php

return [
    Skrepr\IdType\SkreprIdTypeBundle::class => ['all' => true],
];

使用方法

要生成一个 UuidType

bin/console make:id-type [--register] <id_name>

其中 id_name 是类似于 "user_id" 的内容。

使用此生成器命令,将生成两个文件(src/ValueObject/UserId.phpsrc/Persistence/Doctrine/UserIdType.php),如果提供了 --register 选项,也将新类型添加到 config/packages/doctrine.yaml 中。

如果您使用的是自动配置,则不需要注册,因为服务标签 "skrepr.id-type" 将自动将类型注册到 doctrine。

要在您的实体中使用此新 ID(例如

<?php

declare(strict_types=1);

namespace App\Entity;

use App\ValueObject\UserId;
use Doctrine\ORM\Mapping as ORM;

#[ORM\Entity]
class User
{
    #[ORM\Id]
    #[ORM\Column(type: UserId::TYPE)]
    public readonly UserId $id;
    
    #[ORM\Column(type: 'string')]
    public string $name;
    
    public function __construct(string $name)
    {
        $this->id = UserId::generate();
        $this->name = $name;
    }
}

请参阅示例目录,了解 make:id-type 生成的文件。

要生成新的 ID,您可以使用静态的 generate 函数

$newId = UserId::generate();

您也可以向构造函数提供 UUID 或字符串

$userId = new UserId('00000000-0000-0000-0000-000000000000');
// or
$userId = new UserId( \Symfony\Component\Uid\Uuid::v4() );

自动配置

默认情况下,创建的 ID 可以与 Symfony 的自动配置一起使用。要将现有的 ID 升级到此系统,您必须执行以下操作(在本例中我们使用 "UserId")。

  1. 从 config/packages/doctrine.yaml 中删除 'user_id'-行
    doctrine:
        dbal:
            types:
                user_id: App\Persistence\Doctrine\UserIdType
  2. 将服务标签 'skrepr.id-type' 添加到 App\Persistence\Doctrine\UserIdType
    #[AutoconfigureTag('skrepr.id-type')]
    class UserIdType extends AbstractUuidType 
  3. (可选)删除 App\Persistence\Doctrine\UserIdType::getName 函数
  4. (可选)向 App\ValueObject\TestId 添加一个常量(如果执行了第 3 步,则必需)
    public const string TYPE = 'user_id';

您也可以一次性将标签添加到所有自定义类型,因为 skrepr/id-type 的编译器将检查是否为 AbstractUuidType 的子类

# config/service.yaml
    App\Persistence\Doctrine\:
        resource: '../src/Persistence/Doctrine/'
        tags:
            - { name: 'skrepr.id-type' }