将相同的值从一个实体复制到另一个实体


Copy same value From Entity to Entity

我有两个实体

评论

和禁止评论

实体具有相同的字段,当一个评论被禁止时,从评论实体中删除对象并在禁止评论中复制

现在我使用这个脚本Symfony 2 - 将实体克隆到不同的表

$oldEntity = $oldEntity;
$newEntity = new NewEntity();
$oldReflection = new 'ReflectionObject($oldEntity);
$newReflection = new 'ReflectionObject($newEntity);
foreach ($oldReflection->getProperties() as $property) {
    if ($newReflection->hasProperty($property->getName())) {
        $newProperty = $newReflection->getProperty($property->getName());
        $newProperty->setAccessible(true);
        $newProperty->setValue($newEntity, $property->getValue($oldEntity));
    }
}

但是我必须将所有变量更改为公共...

有更好的方法来复制内容吗?

我尝试使用克隆

$BannedComments = new BannedComments();
$BannedComments = clone $Comments;
$em->persist($BannedComments);

但是保存在评论中而不是在禁止评论中,因为当我做克隆评论时,禁止评论是评论的完整性

在我看来,这是一个非常具体的用例。注释实体是否具有许多属性?如果没有,您可以编写一个临时函数来接收 Comment 对象并返回 BannedComment 对象。

使用吸气剂和二传手以避免公开它们。

如果坚持使用泛型方法,请使用方法调用而不是属性访问,但有时,通用方法有点矫枉过正,并且浪费了具体、非重复用例的时间。