深入克隆一个对象:克隆vs序列化 [英] Deep cloning an object : Clone vs Serialize

查看:175
本文介绍了深入克隆一个对象:克隆vs序列化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个函数duplicateCourseAction,其目的是...复制一个Course对象

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.

我发现了unserialize serialize(object))trick:

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");
}

但是我在Doctrine中有这个错误:

But I have this error with Doctrine :

注意:未定义的索引:000000003ed2e9ea00000000ee270fde在/home/mart_q/Diderot/ent/vendor/doctrine/orm/lib/Doctrine/ORM/UnitOfWork.php行2776

推荐答案

您可以通过覆盖 __ clone()方法来控制什么是克隆的您的课程实体。您可以将 id 设置为 null ,如果需要深入复制,则可以克隆引用的对象。

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.

这篇关于深入克隆一个对象:克隆vs序列化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆