简体   繁体   English

Doctrine如何设置私有ID

[英]How does Doctrine set private IDs

In PHP, I can create a model with a private/protected $id variable and no setter. 在PHP中,我可以创建一个带有private / protected $id变量且没有setter的模型。

Doctrine ORM is able to set that property when the object is saved/loaded. Doctrine ORM能够在保存/加载对象时设置该属性。

How does this work internally? 这在内部如何运作? I assume this is handled by serialization, but I haven't been able to find the code responsible of this behavior. 我假设这是由序列化处理的,但我无法找到负责此行为的代码。

The first time doctrine instantiates an entity (such as a User ), it does this: 第一次doctrine实例化一个实体(例如User )时,它会这样做:

$this->prototype = unserialize(sprintf('O:%d:"%s":0:{}', strlen($this->name), $this->name));

Which creates an object of that type without calling its constructor (deserialization avoids a call to __construct , and they do this intentionally so they don't have to worry about what your constructor looks like or does). 在不调用构造函数的情况下创建该类型的对象(反序列化避免了对__construct的调用,并且他们故意这样做,因此他们不必担心构造函数的外观或内容)。

After the first object has been initialized, Doctrine uses clone to make new instances of the same object type. 初始化第一个对象后,Doctrine使用clone创建相同对象类型的新实例。

$entity = clone $this->prototype;

From the cloned objects, it will: 从克隆的对象,它将:

$reflection = new \ReflectionObject($entity);
$property = $reflection->getProperty('idField');
$property->setAccessible(true);
$property->setValue($entity, 123);

The actual code to do this is more complex due to Doctrine's support from compound primary keys, but this should hopefully guide you the right direction. 由于Doctrine对复合主键的支持,实际执行此操作的代码更为复杂,但这有助于指导您正确的方向。

Doctrine ORM uses reflection to assign identifiers . Doctrine ORM使用反射分配标识符 This is done in the class metadata of your entity. 这是在您的实体的类元数据中完成的。

Un-serialization is only used to create new instances (blueprints) of your entities when the ORM has to instantiate them internally without using constructor params. 当ORM必须在不使用构造函数参数的情况下在内部实例化它们时,非序列化仅用于创建实体的新实例 (蓝图)。 Once a blueprint is available, it is cloned for each new requested instance. 一旦蓝图可用,就会为每个新请求的实例克隆它。

There's a blogpost on the official website explaining how Doctrine creates new instances of your entities. 官方网站上有一个博客文章, 解释了Doctrine如何创建实体的新实例

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM