entities-in-session.rst 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. Entities in the Session
  2. =======================
  3. There are several use-cases to save entities in the session, for example:
  4. 1. User object
  5. 2. Multi-step forms
  6. To achieve this with Doctrine you have to pay attention to some details to get
  7. this working.
  8. Merging entity into an EntityManager
  9. ------------------------------------
  10. In Doctrine an entity objects has to be "managed" by an EntityManager to be
  11. updateable. Entities saved into the session are not managed in the next request
  12. anymore. This means that you have to register these entities with an
  13. EntityManager again if you want to change them or use them as part of
  14. references between other entities. You can achieve this by calling
  15. ``EntityManager#merge()``.
  16. For a representative User object the code to get turn an instance from
  17. the session into a managed Doctrine object looks like this:
  18. .. code-block:: php
  19. <?php
  20. require_once 'bootstrap.php';
  21. $em = GetEntityManager(); // creates an EntityManager
  22. session_start();
  23. if (isset($_SESSION['user']) && $_SESSION['user'] instanceof User) {
  24. $user = $_SESSION['user'];
  25. $user = $em->merge($user);
  26. }
  27. .. note::
  28. A frequent mistake is not to get the merged user object from the return
  29. value of ``EntityManager#merge()``. The entity object passed to merge is
  30. not necessarily the same object that is returned from the method.
  31. Serializing entity into the session
  32. -----------------------------------
  33. Entities that are serialized into the session normally contain references to
  34. other entities as well. Think of the user entity has a reference to his
  35. articles, groups, photos or many other different entities. If you serialize
  36. this object into the session then you don't want to serialize the related
  37. entities as well. This is why you should call ``EntityManager#detach()`` on this
  38. object or implement the __sleep() magic method on your entity.
  39. .. code-block:: php
  40. <?php
  41. require_once 'bootstrap.php';
  42. $em = GetEntityManager(); // creates an EntityManager
  43. $user = $em->find("User", 1);
  44. $em->detach($user);
  45. $_SESSION['user'] = $user;
  46. .. note::
  47. When you called detach on your objects they get "unmanaged" with that
  48. entity manager. This means you cannot use them as part of write operations
  49. during ``EntityManager#flush()`` anymore in this request.