pugx / shortid-doctrine
短id-php 的 Doctrine 类型
v1.3.0
2024-05-04 13:43 UTC
Requires
- php: ^8.1
- doctrine/orm: ^2.7 || ^3.0
- pugx/shortid-php: ^1.0
Requires (Dev)
- dg/bypass-finals: ^1.6
- phpunit/phpunit: ^9.6
This package is auto-updated.
Last update: 2024-09-06 05:41:37 UTC
README
为 PHP 中的 Doctrine 字段类型 提供的 ShortId。
安装
运行以下命令
composer require pugx/shortid-doctrine
注意: 如果你使用 Symfony,你应该要求 pugx/shortid-doctrine-bundle。
例子
要配置 Doctrine 使用 shortid
作为字段类型,你需要在你的引导文件中设置以下内容
<?php \Doctrine\DBAL\Types\Type::addType('shortid', 'PUGX\Shortid\Doctrine\ShortidType'); $entityManager->getConnection()->getDatabasePlatform()->registerDoctrineTypeMapping('shortid', 'shortid');
然后,在你的实体中,你可以通过将 @Column
类型设置为 shortid
来注释属性。
你可以在构造函数中为属性生成一个 PUGX\Shortid\Shortid
对象,或者使用内置的生成器。
构造函数中手动创建 ShortId 的示例
<?php use PUGX\Shortid\Shortid; /** * @Entity * @Table */ class Product { /** * @var Shortid * * @Id * @Column(type="shortid") * @GeneratedValue(strategy="NONE") */ private $id; public function __construct(?Shortid $id = null) { $this->id = $id ?? Shortid::generate(); } public function getId(): Shortid { return $this->id; } }
自动生成 shortid 的示例
<?php use PUGX\Shortid\Shortid; /** * @Entity * @Table */ class Product { /** * @var Shortid * * @Id * @Column(type="shortid") * @GeneratedValue(strategy="CUSTOM") * @CustomIdGenerator(class="PUGX\Shortid\Doctrine\Generator\ShortidGenerator") */ private $id; public function getId(): Shortid { return $this->id; } }
如果你想要自定义 ShortId 的长度,你可以在 Column 注解中使用 length
选项。 示例
<?php use PUGX\Shortid\Shortid; /** * @Entity * @Table */ class Product { /** * @var Shortid * * @Id * @Column(type="shortid", length=5) * @GeneratedValue(strategy="NONE") */ private $id; public function __construct() { $this->id = Shortid::generate(5); } }
如果你想要自定义字母表和/或使用内置生成器,你需要在引导文件中设置 ShortId
<?php \Doctrine\DBAL\Types\Type::addType('shortid', 'PUGX\Shortid\Doctrine\ShortidType'); $entityManager->getConnection()->getDatabasePlatform()->registerDoctrineTypeMapping('shortid', 'shortid'); $factory = new \PUGX\Shortid\Factory(); // alphabet must be 64 characters long $factory->setAlphabet('é123456789àbcdefghìjklmnòpqrstùvwxyzABCDEFGHIJKLMNOPQRSTUVWX.!@|'); // length must be between 2 and 20 $factory->setLength(5); PUGX\Shortid\Shortid::setFactory($factory);
然后,你必须注意配置每个 ShortId 属性以具有 相同的长度(在此示例中为 5
)。