title: Deep cloning an object : Clone vs Serialize
body: <p>I have this function duplicateCourseAction whose goal is to ... duplicate a Course object</p>
  
  <pre><code>public function duplicateCourseAction(Request $request) {
      if ($this-&gt;getRequest()-&gt;isXmlHttpRequest() == false) {
          return new Response("Bad request", 405);
      }
  
      $em = $this-&gt;getDoctrine()-&gt;getManager();
      $parameters = $request-&gt;request-&gt;all();
      $course = $em-&gt;getRepository('EntTimeBundle:Course')-&gt;findOneById($parameters['id']);
      $duplicate = clone $course;
      $duplicate-&gt;setDate(new \DateTime($parameters['date']));
      $em-&gt;persist($duplicate);
      $em-&gt;flush();
      return new Response("200");
  }
  </code></pre>
  
  <p>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.</p>
  
  <p>I discovered the unserialize(serialize(object)) trick :</p>
  
  <pre><code>public function duplicateCourseAction(Request $request) {
      if ($this-&gt;getRequest()-&gt;isXmlHttpRequest() == false) {
          return new Response("Bad request", 405);
      }
  
      $em = $this-&gt;getDoctrine()-&gt;getManager();
      $parameters = $request-&gt;request-&gt;all();
      $course = $em-&gt;getRepository('EntTimeBundle:Course')-&gt;findOneById($parameters['id']);
      $duplicate = unserialize(serialize($course));
      $duplicate-&gt;setDate(new \DateTime($parameters['date']));
      $em-&gt;persist($duplicate);
      $em-&gt;flush();
      return new Response("200");
  }
  </code></pre>
  
  <p>But I have this error with Doctrine :</p>
  
  <p><strong>Notice: Undefined index: 000000003ed2e9ea00000000ee270fde in /home/mart_q/Diderot/ent/vendor/doctrine/orm/lib/Doctrine/ORM/UnitOfWork.php line 2776</strong></p>