Generate Uuid manually in constructor or via UuidGenerator annotation

不羁的心 提交于 2020-01-06 15:01:52

问题


I am switching to Ramsey\Uuid and don't know what is the intended way to generate the Uuids.

Either as shown in the examples with an anntoation:

/**
 * @var UuidInterface
 *
 * @ORM\Id
 * @ORM\Column(type="uuid", unique=true)
 * @ORM\GeneratedValue(strategy="CUSTOM")
 * @ORM\CustomIdGenerator(class="Ramsey\Uuid\Doctrine\UuidGenerator")
 */
private $id;


public function __construct() {
}

Or manually in the constructor:

/**
 * @var UuidInterface
 *
 * @ORM\Id
 * @ORM\Column(type="uuid", unique=true)
 */
private $id;


public function __construct() {
    $this->id = Uuid::uuid4();
}

In the second case, I do not understand how an existing id would be set during hydration. I added a public setter for testing purposes, but it is not called! In my understanding, when loading from db, a new object is created, which executes the constructor and hence sets a new uuid. Then somehow, this uuid must be replaced by the one from the db record. Am I missing something?

However the big advantage that the id is available immediately is gone when using the annotation, since the generation only takes place when calling $em->persist(...).

There are also variants out there where the constructor takes an optional uuid argument and uses it if not null.

来源:https://stackoverflow.com/questions/53045546/generate-uuid-manually-in-constructor-or-via-uuidgenerator-annotation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!