title: Symfony2 serialize entity object to session
body: <p>I want to save one of my entity objects into the session, but as I'm doing so, I'm getting the following two errors:</p>
  
  <blockquote>
    <p>Exception:
    Symfony\Bundle\FrameworkBundle\DataCollector\RequestDataCollector::serialize()
    must return a string or NULL</p>
  </blockquote>
  
  <p>and</p>
  
  <blockquote>
    <p>ErrorException: Notice: serialize(): "id" returned as member
    variable from __sleep() but does not exist in
    /var/www/clients/client71/web256/web/_dev_fd/kkupon/vendor/symfony/src/Symfony/Component/HttpKernel/DataCollector/DataCollector.php
    line 29</p>
  </blockquote>
  
  <p>My code goes like this:</p>
  
  <pre><code>$offer = $this-&gt;getEntityManager()-&gt;getRepository('KkuponMainBundle:Offer')-&gt;find($offer_id);
  $request-&gt;getSession()-&gt;set('offer', $offer);
  </code></pre>
  
  <p>How could I get it right?</p>
  
  <p>Thank you.</p>
  
  <p><strong>UPDATE</strong>
  With Rowgm's help I could fix this problem by setting properties protected instead of private. The only problem I have is after <em>reading</em> the entity from the session the EntityManager does not know about it, and if I add the object(from the session) to another object(there is OneToMany relationship between them), it won't work.</p>
  
  <pre><code>&lt;?php
  $offer = $this-&gt;get('session')-&gt;get('offer');
  $coupon = new Coupon();
  $coupon-&gt;setOffer($offer);
  $this-&gt;em-&gt;persist($coupon);
  $this-&gt;em-&gt;flush();
  </code></pre>
  
  <p>This raises an error, because coupon has an object property which according to the EntityManager is not in the database(actually it is in the DB, I put to the session from the DB).</p>
  
  <pre><code>&lt;?php
  $offer = $this-&gt;get('session')-&gt;get('offer');
  echo $this-&gt;em-&gt;getUnitOfWork()-&gt;isInIdentityMap($offer) ? "yes":"no"; //result: no
  </code></pre>
  
  <p>One solution can be:
       <code>$offer = $this-&gt;em-&gt;merge($offer);</code></p>
  
  <p>But this doesnt seem to be the best one. I'd like my EntityManager to perceive entity objects stored in session without telling it each time.
  Any idea?</p>