定制 enumeum/doctrine-enums 二次开发

按需修改功能、优化性能、对接业务系统,提供一站式技术支持

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

enumeum/doctrine-enums

Composer 安装命令:

composer require enumeum/doctrine-enums

包简介

Doctrine extension to manage enumerations in PostgreSQL

README 文档

README

This package contains an extension for Doctrine ORM and DBAL which offer enum management functionality in a PostgreSQL database. Yes, enumerations in DB is bad practice, and you should avoid to use them. But sometimes DB management needs Enums as a simple constraint on certain fields. This package provides a transparent approach to adding PHP enums as database types and using them with appropriate fields in Doctrine entities.

Requirements

Minimum PHP version is 8.1.

Installation

composer require enumeum/doctrine-enums

Usage

Enumeum attribute for PHP enum:

  • #[Enumeum\DoctrineEnum\Attribute\EnumType(name: 'type_name')] this attribute tells that this enum is database type. By default, it creates type in database with its own cases.

Enum setup

<?php
namespace App\Enums;

use Enumeum\DoctrineEnum\Attribute\EnumType;

#[EnumType(name: 'status_type')]
enum StatusType: string
{
    case STARTED = 'started';
    case PROCESSING = 'processing';
    case FINISHED = 'finished';
}

Entity setup

Please note that the configuration of the entity is no different from the usual one. Doctrine supports "enumType" property and converts it transparently.

<?php
namespace App\Entities;

use Doctrine\DBAL\Types\Types;
use Doctrine\ORM\Mapping as ORM;
use App\Enum\StatusType;

/**
 * @ORM\Entity
 * @ORM\Table(name="entity")
 */
#[ORM\Entity]
#[ORM\Table(name: 'entity')]
class Entity
{
    /**
     * @ORM\Id
     * @ORM\Column(type="integer")
     */
    #[ORM\Id]
    #[ORM\Column(type: Types::INTEGER)]
    private int $id;

    /**
     * @ORM\Column(type="string", enumType=StatusType::class, options={"comment":"Comment"})
     */
    #[ORM\Column(type: Types::STRING, enumType: StatusType::class, options: ['comment' => 'Comment'])]
    private StatusType $status;

    public function __construct(
        int $id,
        StatusType $status,
    ) {
        $this->id = $id;
        $this->status = $status;
    }

    public function getId(): int
    {
        return $this->id;
    }

    public function getStatus(): StatusType
    {
        return $this->status;
    }
}

DBAL Configuration

<?php

namespace App;

use Enumeum\DoctrineEnum\Definition\DefinitionRegistryLoader;
use Enums\BaseStatusType;

$enumClassNames = [
    BaseStatusType::class,
    // ...
];

$enumDirPaths = [
    [
        'path' => __DIR__.'/../Enums',
        'namespace' => 'App\Enums',
    ]
    // ...
];

$loader = DefinitionRegistryLoader::create(new EnumClassLocator([]), $enumClassNames, $enumDirPaths);

Additional types or directories can be added by the appropriate methods one or more

$loader->loadType(BaseStatusType::class);
$loader->loadTypes([BaseStatusType::class]);

$loader->loadDir([
    'path' => __DIR__.'/../Enums',
    'namespace' : 'App\Enums',
]);
$loader->loadDirs([
    [
        'path' => __DIR__.'/../Enums',
        'namespace' : 'App\Enums',
    ],
]);

Filled loader provides Enumeum\DoctrineEnum\Definition\DefinitionRegistry instance with collection of enums definitions. Every call creates new Registry instance.

$registry = $loader->getRegistry();

DBAL Schema manipulation needs to have new types loaded thus use special Enumeum\DoctrineEnum\Type\TypeRegistryLoader for that.

TypeRegistryLoader::load($registry->getDefinitions());

Next step is to create Enumeum\DoctrineEnum\EnumTool and use it to generate SQL queries for database Enums persistence or update Database directly.

<?php

namespace App;

use Enumeum\DoctrineEnum\EnumTool;

$tool = EnumTool::create($registry, $doctrineDbalConnection);

// Updates database with configured enums
$tool->createSchema();
// ... OR generates SQL queries for update 
$sql = $tool->getCreateSchemaSql();

ORM Configuration

ORM part needs just adding Enumeum\DoctrineEnum\EventSubscriber\PostGenerateSchemaSubscriber into Doctrine's EventManager

<?php

namespace App;

use Doctrine\Common\EventManager;
use Doctrine\ORM\EntityManager;
use Enumeum\DoctrineEnum\EnumUsage\TableColumnRegistry;
use Enumeum\DoctrineEnum\EventSubscriber\PostGenerateSchemaSubscriber;

$evm = new EventManager();
$em = EntityManager::create($params, $config, $evm);
$evm->addEventSubscriber(new PostGenerateSchemaSubscriber(
    $registry,
    new TableColumnRegistry($em->getConnection()),
));

Usage

If you have changed enums values, their structure, adding or dropping types then use Enumeum\DoctrineEnum\EnumTool. It will generate SQL queries to synchronize configured enums or updates database directly. After that if it is required to change not just enums but also a schema then do schema diff/update.

Running Tests

To set up and run the tests, follow these steps:

  • Install Docker and ensure you have docker-compose and make (optional)
  • From the project root, run make start to start containers in daemon mode (or using docker-compose up -d --build --remove-orphans --force-recreate)
  • Enter the container via make console (or using docker-compose exec php bash)
  • Check that you are in root directory /var/www, if neither then navigate using: cd /var/www
  • Install Composer dependencies via composer install
  • Run the tests with make test from out of container (or using bin/phpunit -c tests/ inside container)

Possible future feature

Command for removing Enum value without recreating. https://postgrespro.ru/list/thread-id/2388881

enumeum/doctrine-enums 适用场景与选型建议

enumeum/doctrine-enums 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 5.59k 次下载、GitHub Stars 达 2, 最近一次更新时间为 2022 年 10 月 13 日, 在 PHP 生态内属于活跃度较高的组件。

它主要适用于以下技术方向: 「extensions」 「doctrine」 「postgres」 「enum」 「enumeration」 「enumeum」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。

我们在过去多个企业项目中使用过 enumeum/doctrine-enums 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。

围绕 enumeum/doctrine-enums 我们能提供哪些服务?
定制开发 / 二次开发

基于 enumeum/doctrine-enums 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。

BUG 修复 & 性能优化

线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。

项目外包 & 长期维护

承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。

yvsm@zunyunkeji.com QQ:316430983 微信:yvsm316 西安尊云信息科技 · 专注 PHP / Go / 分布式系统研发

统计信息

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

GitHub 信息

  • Stars: 2
  • Watchers: 2
  • Forks: 2
  • 开发语言: PHP

其他信息

  • 授权协议: MIT
  • 更新时间: 2022-10-13