pchapl / ids
Symfony 扩展包,用于 doctrine 自定义类型自动配置
2.0.0
2023-10-06 15:42 UTC
Requires
- php: ^8.0.0
- doctrine/dbal: ^3.0|^2.8.0
- symfony/config: ^5.0|^6.0
- symfony/dependency-injection: ^5.0|^6.0
- symfony/http-kernel: ^5.0|^6.0
Requires (Dev)
- phpunit/phpunit: ^9.5
- roave/security-advisories: dev-latest
README
使用方法
composer require pchapl/ids
在 config/bundles.php 中启用扩展包
PChapl\DoctrineIdBundle\DoctrineIdBundle::class => ['all' => true],
创建 Id 类,例如
namespace App\Data; use PChapl\DoctrineIdBundle\Id\Base; final class AccountId extends Base { }
使用 config/packages/doctrine_id.yaml 中的类型配置扩展包
doctrine_id: types: account_id: App\Data\AccountId user_id: App\Data\UserId
然后在实体中使用
#[ORM\Entity] class Account { #[ORM\Column(type="account_id")] private AccountId $id; public function __construct(AccountId $id) { $this->id = $id; } public function getId(): AccountId { return $this->id; }
实例化 ids 有两种方式:为 Base::new 方法实现 Factory 接口,或者直接使用 Base::fromValue 方法并传递生成的字符串 id
/** @var \Hidehalo\Nanoid\Client $nanoidClient */ $factory = new class($nanoidClient) implements \PChapl\DoctrineIdBundle\Id\Factory { public function __construct(private \Hidehalo\Nanoid\Client $nano) { } public function generate(): string { return $this->nano->generateId(); } }; $account1 = new Account(AccountId::new($factory)); $account2 = new Account(AccountId::fromValue($nanoidClient->generateId())); $account3 = new Account(AccountId::fromValue(\Ramsey\Uuid\Uuid::uuid4()->toString()));