wakeapp/dbal-enum-type

此包已被废弃,不再维护。未建议替代包。

提供在Doctrine中处理ENUM类型的基本功能

v1.1.1 2021-07-05 02:31 UTC

This package is auto-updated.

Last update: 2021-12-05 10:22:45 UTC


README

Latest Stable Version Total Downloads

简介

组件提供了在Doctrine中注册新的数据类型ENUM的基本功能。同时支持doctrine:schema:update对ENUM的处理。

重要:为了使doctrine:schema:update命令行中的ENUM支持正确实现,请不要指定数据库驱动器。

  • 正确的工作方式 - //user:pa$$word@host:3306/db_name
  • 将无法工作 - mysql://user:pa$$word@host:3306/db_name

安装

打开控制台,切换到项目目录,执行以下命令以安装此组件的稳定版本:

    composer require wakeapp/dbal-enum-type

此命令假定已安装并全局可用Composer

使用示例

以语言枚举为例。首先,我们需要创建一个包含可用语言的类。

<?php declare(strict_types=1);

namespace App\AcmeBundle\Entity\Enum;

class LanguageListEnum
{
    public const RU = 'ru';
    public const EN = 'en';
    public const DE = 'de';
}

为了将我们的枚举注册为新的Doctrine数据类型,我们需要创建另一个类。

<?php declare(strict_types=1);

namespace App\AcmeBundle\Doctrine\DBAL\Types;

use App\AcmeBundle\Entity\Enum\LanguageListEnum;
use Wakeapp\Component\DbalEnumType\Type\AbstractEnumType;

class LanguageListEnumType extends AbstractEnumType
{
    /**
     * {@inheritdoc}
     */
    public static function getEnumClass(): string
    {
        return LanguageListEnum::class;
    }
    
    /**
     * {@inheritdoc}
     */
    public static function getTypeName(): string
    {
        return 'language_list_enum';
    }
}

创建必要的类后,只需在Doctrine DBAL中注册它们。要注册新的ENUM类型,请参阅Doctrine官方文档自定义映射类型

<?php declare(strict_types=1);

\Doctrine\DBAL\Types\Type::addType(LanguageListEnumType::getTypeName(), LanguageListEnumType::class);

如果您使用的是Symfony,请参阅相应的文档部分 - 如何使用Doctrine DBAL

首先需要注册新的全局数据类型enum

doctrine:
    dbal:
        mapping_types:
            enum: string

然后需要设置具体类型的枚举列表,这可以通过两种方式实现。第一种是经典的通过添加到配置文件中Doctrine

doctrine:
    dbal:
        types:
            # Где ключ это LanguageListEnumType::getTypeName() и значение LanguageListEnumType::class
            language_list_enum: App\AcmeBundle\Doctrine\DBAL\Types\LanguageListEnumType

第二种方式适用于使用单独的bundle。通过boot方法进行注册。

<?php declare(strict_types=1);

namespace App\AcmeBundle;

use App\AcmeBundle\Doctrine\DBAL\Types\LanguageListEnumType;
use Doctrine\DBAL\Types\Type;
use Symfony\Component\HttpKernel\Bundle\Bundle;

class AppAcmeBundleBundle extends Bundle
{
    public function boot()
    {
        Type::addType(LanguageListEnumType::getTypeName(), LanguageListEnumType::class);

        parent::boot();
    }
}

额外

与Symfony一起使用

在使用Symfony Framework的情况下,需要将EnumEventSubscriber类注册为带有doctrine.event_subscriber标签的服务。

    wakeapp.dbal_enum_type.event_subscriber.enum_event:
        tags:
            - { name: doctrine.event_subscriber, connection: default }

还需要在doctrine/doctrine-bundle的配置中指定driver_class

doctrine:
    dbal:
        driver_class:   Wakeapp\Component\DbalEnumType\Driver\PDOMySql\EnumAwareDriver

枚举值重写

如果需要重写基于类常量的方法getEnumClass中定义的enum值列表,可以调用setValues方法。

许可证

license