Uuidable

← Uuidable

Ashterix

docs: Doctrine section with Doctrine Behaviors and Doctrine Helper (uk + en)

en/docs/doctrine/doctrine-behaviors/uuidable.md new file +34 −0

1 + # Uuidable
2 +
3 + Adds a version 4 UUID to an entity, generated on the first save.
4 +
5 + ## Entity
6 +
7 + ```php
8 + use Doctrine\ORM\Mapping as ORM;
9 + use Ufo\DoctrineBehaviors\Contract\Entity\UuidableInterface;
10 + use Ufo\DoctrineBehaviors\Model\Uuidable\UuidableTrait;
11 +
12 + #[ORM\Entity]
13 + class BlogPost implements UuidableInterface
14 + {
15 + use UuidableTrait;
16 +
17 + #[ORM\Id, ORM\GeneratedValue, ORM\Column]
18 + private ?int $id = null;
19 + }
20 + ```
21 +
22 + ## How it works
23 +
24 + * The bundle maps `uuid` as a nullable string column. It is an extra field, not the primary key — the entity identifier stays yours.
25 + * On `prePersist` `generateUuid()` is called: if there is no UUID yet, `Ramsey\Uuid\Uuid::uuid4()` is created. A UUID set manually with `setUuid()` is not overwritten.
26 + * `getUuid()` returns `Ramsey\Uuid\UuidInterface` even if a string came from the database.
27 +
28 + ```php
29 + $post = new BlogPost();
30 + $entityManager->persist($post);
31 + $entityManager->flush();
32 +
33 + $post->getUuid()->toString(); // e.g. '1ee9aa1b-6510-4105-92b9-7171bb2f3089'
34 + ```