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

Uuidable

Adds a version 4 UUID to an entity, generated on the first save.

Entity

use Doctrine\ORM\Mapping as ORM;
use Ufo\DoctrineBehaviors\Contract\Entity\UuidableInterface;
use Ufo\DoctrineBehaviors\Model\Uuidable\UuidableTrait;

#[ORM\Entity]
class BlogPost implements UuidableInterface
{
    use UuidableTrait;

    #[ORM\Id, ORM\GeneratedValue, ORM\Column]
    private ?int $id = null;
}

How it works

  • The bundle maps uuid as a nullable string column. It is an extra field, not the primary key — the entity identifier stays yours.
  • 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.
  • getUuid() returns Ramsey\Uuid\UuidInterface even if a string came from the database.
$post = new BlogPost();
$entityManager->persist($post);
$entityManager->flush();

$post->getUuid()->toString(); // e.g. '1ee9aa1b-6510-4105-92b9-7171bb2f3089'