nepada / consistence-doctrine
此包已被 废弃,不再维护。未建议替代包。
Doctrine 的 Consistence 枚举类型。
v1.1.1
2022-08-13 20:15 UTC
Requires
- php: >=7.4.0 <8.2
- consistence/consistence: ^2.0@dev
- doctrine/dbal: ^2.6@dev || ^3.0@dev
Requires (Dev)
- consistence-community/consistence: ^2.0@dev
- mockery/mockery: 1.5.0
- nepada/coding-standard: 7.5.2
- nepada/phpstan-nette-tester: 0.4.0
- nette/tester: 2.4.2
- php-parallel-lint/php-parallel-lint: 1.3.2
- phpstan/phpstan: 1.8.2
- phpstan/phpstan-mockery: 1.1.0
- phpstan/phpstan-strict-rules: 1.3.0
- shipmonk/phpstan-rules: 1.0.1
- spaze/phpstan-disallowed-calls: 2.5.0
This package is auto-updated.
Last update: 2022-08-13 20:17:58 UTC
README
包已废弃
此包被认为是过时且已废弃。由于 PHP 8.1 引入了原生的枚举支持,因此不再需要用户空间的枚举实现,也不需要将它们自定义集成到 Doctrine。
安装
通过 Composer
$ composer require nepada/consistence-doctrine
用法
定义 Doctrine 枚举类型
/** * @phpstan-extends \Nepada\ConsistenceDoctrine\StringEnumType<\FooEnum> */ class FooEnumType extends \Nepada\ConsistenceDoctrine\StringEnumType { protected function getEnumClassName(): string { return \FooEnum::class; } }
您可以根据枚举值选择从 StringEnumType
、IntegerEnumType
、FloatEnumType
或 BooleanEnumType
继承。
在 Doctrine 中注册创建的类型
\Doctrine\DBAL\Types\Type::addType(\FooEnum::class, \FooEnumType::class);
在 Nette 中,通过 nettrine/dbal 集成,您可以在配置中注册这些类型
dbal: connection: types: FooEnum: FooEnumType
在实体中使用类型
use Doctrine\ORM\Mapping as ORM; /** * @ORM\Entity */ class SomeEntity { /** @ORM\Column(type=\FooEnum::class, nullable=false) */ private \FooEnum $foo; // ... }
在查询构建器中使用枚举
$result = $repository->createQueryBuilder('bar') ->select('bar.foo') // FooEnum instances are created during hydratation ->where('bar.foo = :fooEnum') ->setParameter('fooEnum', \FooEnum::get(\FooEnum::VALUE), \FooEnum::class) // enum instance gets serialized ->getQuery() ->setMaxResults(1) ->getSingleResult();
PHPStan 支持(通过 phpstan/phpstan-doctrine
)
抽象枚举类型类被标记为 PHPStan 泛型,并为它们的 convert*
方法定义了适当的类型提示。这意味着您可以通过 ReflectionDescriptor
教导 PHPStan 您的定制枚举类型。
services: - factory: PHPStan\Type\Doctrine\Descriptors\ReflectionDescriptor(FooEnumType) tags: [phpstan.doctrine.typeDescriptor]
与官方 consistence/consistence-doctrine
的差异
官方集成 consistence/consistence-doctrine
使用 postload 实体事件将数据库中存储的数据转换为枚举实例。
这种方法的主要优点是您不需要为每个枚举创建和注册新的 Doctrine 类型。
缺点是
- 您不能使用原生属性类型提示为实体枚举属性。
- 当您不填充实体时,您将获得枚举值而不是枚举实例。
- 没有简单的方法可以使 PHPStan 理解并检查您的枚举字段的 Doctrine 和 PHP 类型。