implementing-wakeup-or-clone.rst 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. Implementing Wakeup or Clone
  2. ============================
  3. .. sectionauthor:: Roman Borschel (roman@code-factory.org)
  4. As explained in the
  5. `restrictions for entity classes in the manual <http://www.doctrine-project.org/documentation/manual/2_0/en/architecture#entities>`_,
  6. it is usually not allowed for an entity to implement ``__wakeup``
  7. or ``__clone``, because Doctrine makes special use of them.
  8. However, it is quite easy to make use of these methods in a safe
  9. way by guarding the custom wakeup or clone code with an entity
  10. identity check, as demonstrated in the following sections.
  11. Safely implementing \_\_wakeup
  12. ------------------------------
  13. To safely implement ``__wakeup``, simply enclose your
  14. implementation code in an identity check as follows:
  15. .. code-block:: php
  16. <?php
  17. class MyEntity
  18. {
  19. private $id; // This is the identifier of the entity.
  20. //...
  21. public function __wakeup()
  22. {
  23. // If the entity has an identity, proceed as normal.
  24. if ($this->id) {
  25. // ... Your code here as normal ...
  26. }
  27. // otherwise do nothing, do NOT throw an exception!
  28. }
  29. //...
  30. }
  31. Safely implementing \_\_clone
  32. -----------------------------
  33. Safely implementing ``__clone`` is pretty much the same:
  34. .. code-block:: php
  35. <?php
  36. class MyEntity
  37. {
  38. private $id; // This is the identifier of the entity.
  39. //...
  40. public function __clone()
  41. {
  42. // If the entity has an identity, proceed as normal.
  43. if ($this->id) {
  44. // ... Your code here as normal ...
  45. }
  46. // otherwise do nothing, do NOT throw an exception!
  47. }
  48. //...
  49. }
  50. Summary
  51. -------
  52. As you have seen, it is quite easy to safely make use of
  53. ``__wakeup`` and ``__clone`` in your entities without adding any
  54. really Doctrine-specific or Doctrine-dependant code.
  55. These implementations are possible and safe because when Doctrine
  56. invokes these methods, the entities never have an identity (yet).
  57. Furthermore, it is possibly a good idea to check for the identity
  58. in your code anyway, since it's rarely the case that you want to
  59. unserialize or clone an entity with no identity.