3 回答

TA贡献1887条经验 获得超5个赞
通常,实现所需目标的方法就是不使用设置器并在实体实例化期间填充字段。
class Foo
private $number;
private $createdAt;
public __construct() {
$this->createdAt = new DateTimeImmutable();
}
public getCreatedAt(): DateTimeImmutable {
return $this->createdAt;
}
public setNumber(int $number) {
$this->number = $number;
}
public getNumber(): int { return $this->int; }
}
这样你就可以知道你的实体将始终有一个createdAt不依赖于 DB 或 Doctrine 的有效字段,并且由于你没有设置器,你不能从外部修改值(不诉诸反射或其他技巧)。

TA贡献1853条经验 获得超9个赞
这不是真正的约束。
你可以这样做
class Foo
{
/**
* @var \DateTime
* @ORM\Column(type="datetime")
*/
private $createdAt;
public __construct() {
$this->createdAt = new DateTime();
}
public getCreatedAt(): DateTime {
return $this->createdAt;
}
...
}
顺便说一下,看看 Gedmo/Timestampable,它为您的实体和映射提供了一些东西。
没有找到匹配的内容?试试慕课网站内搜索吧
- 3 回答
- 0 关注
- 106 浏览
添加回答
举报