Deep cloning an object : Clone vs Serialize

安稳与你 提交于 2019-12-20 05:36:06

问题


I have this function duplicateCourseAction whose goal is to ... duplicate a Course object

public function duplicateCourseAction(Request $request) {
    if ($this->getRequest()->isXmlHttpRequest() == false) {
        return new Response("Bad request", 405);
    }

    $em = $this->getDoctrine()->getManager();
    $parameters = $request->request->all();
    $course = $em->getRepository('EntTimeBundle:Course')->findOneById($parameters['id']);
    $duplicate = clone $course;
    $duplicate->setDate(new \DateTime($parameters['date']));
    $em->persist($duplicate);
    $em->flush();
    return new Response("200");
}

According to documentations, "clone" keyword make a surface copy (ie. a reference copy). This is clearly not what I want because my Course entity contains many relations to others entities, I would rather want a values copy.

I discovered the unserialize(serialize(object)) trick :

public function duplicateCourseAction(Request $request) {
    if ($this->getRequest()->isXmlHttpRequest() == false) {
        return new Response("Bad request", 405);
    }

    $em = $this->getDoctrine()->getManager();
    $parameters = $request->request->all();
    $course = $em->getRepository('EntTimeBundle:Course')->findOneById($parameters['id']);
    $duplicate = unserialize(serialize($course));
    $duplicate->setDate(new \DateTime($parameters['date']));
    $em->persist($duplicate);
    $em->flush();
    return new Response("200");
}

But I have this error with Doctrine :

Notice: Undefined index: 000000003ed2e9ea00000000ee270fde in /home/mart_q/Diderot/ent/vendor/doctrine/orm/lib/Doctrine/ORM/UnitOfWork.php line 2776


回答1:


You can control what exactly gets cloned by overriding the __clone() method in your Course entity. You can set id to null and clone referenced objects if you need a deep copy.

The serialization/unserialization feels like a hack, so I recommend against using it.




回答2:


Trick here is that you must unset duplicate entity id. Otherwise breaks the logic of the doctrine. Doctrine has some known limitations. Also check this question, its very similar.



来源:https://stackoverflow.com/questions/18592872/deep-cloning-an-object-clone-vs-serialize

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