PersistentObject.php 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233
  1. <?php
  2. /*
  3. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  4. * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  5. * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  6. * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  7. * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  8. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  9. * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  10. * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  11. * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  12. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  13. * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  14. *
  15. * This software consists of voluntary contributions made by many individuals
  16. * and is licensed under the LGPL. For more information, see
  17. * <http://www.doctrine-project.org>.
  18. */
  19. namespace Doctrine\Common\Persistence;
  20. use Doctrine\Common\Persistence\Mapping\ClassMetadata;
  21. use Doctrine\Common\Collections\ArrayCollection;
  22. use Doctrine\Common\Collections\Collection;
  23. /**
  24. * PersistentObject base class that implements getter/setter methods for all mapped fields and associations
  25. * by overriding __call.
  26. *
  27. * This class is a forward compatible implementation of the PersistentObject trait.
  28. *
  29. *
  30. * Limitations:
  31. *
  32. * 1. All persistent objects have to be associated with a single ObjectManager, multiple
  33. * ObjectManagers are not supported. You can set the ObjectManager with `PersistentObject#setObjectManager()`.
  34. * 2. Setters and getters only work if a ClassMetadata instance was injected into the PersistentObject.
  35. * This is either done on `postLoad` of an object or by accessing the global object manager.
  36. * 3. There are no hooks for setters/getters. Just implement the method yourself instead of relying on __call().
  37. * 4. Slower than handcoded implementations: An average of 7 method calls per access to a field and 11 for an association.
  38. * 5. Only the inverse side associations get autoset on the owning side aswell. Setting objects on the owning side
  39. * will not set the inverse side associations.
  40. *
  41. * @example
  42. *
  43. * PersistentObject::setObjectManager($em);
  44. *
  45. * class Foo extends PersistentObject
  46. * {
  47. * private $id;
  48. * }
  49. *
  50. * $foo = new Foo();
  51. * $foo->getId(); // method exists through __call
  52. *
  53. * @author Benjamin Eberlei <kontakt@beberlei.de>
  54. */
  55. abstract class PersistentObject implements ObjectManagerAware
  56. {
  57. /**
  58. * @var ObjectManager
  59. */
  60. private static $objectManager;
  61. /**
  62. * @var ClassMetadata
  63. */
  64. private $cm;
  65. /**
  66. * Set the object manager responsible for all persistent object base classes.
  67. *
  68. * @param ObjectManager $objectManager
  69. */
  70. static public function setObjectManager(ObjectManager $objectManager = null)
  71. {
  72. self::$objectManager = $objectManager;
  73. }
  74. /**
  75. * @return ObjectManager
  76. */
  77. static public function getObjectManager()
  78. {
  79. return self::$objectManager;
  80. }
  81. /**
  82. * Inject Doctrine Object Manager
  83. *
  84. * @param ObjectManager $objectManager
  85. * @param ClassMetadata $classMetadata
  86. */
  87. public function injectObjectManager(ObjectManager $objectManager, ClassMetadata $classMetadata)
  88. {
  89. if ($objectManager !== self::$objectManager) {
  90. throw new \RuntimeException("Trying to use PersistentObject with different ObjectManager instances. " .
  91. "Was PersistentObject::setObjectManager() called?");
  92. }
  93. $this->cm = $classMetadata;
  94. }
  95. /**
  96. * Sets a persistent fields value.
  97. *
  98. * @throws InvalidArgumentException - When the wrong target object type is passed to an association
  99. * @throws BadMethodCallException - When no persistent field exists by that name.
  100. * @param string $field
  101. * @param array $args
  102. * @return void
  103. */
  104. private function set($field, $args)
  105. {
  106. $this->initializeDoctrine();
  107. if ($this->cm->hasField($field) && !$this->cm->isIdentifier($field)) {
  108. $this->$field = $args[0];
  109. } else if ($this->cm->hasAssociation($field) && $this->cm->isSingleValuedAssociation($field)) {
  110. $targetClass = $this->cm->getAssociationTargetClass($field);
  111. if (!($args[0] instanceof $targetClass) && $args[0] !== null) {
  112. throw new \InvalidArgumentException("Expected persistent object of type '".$targetClass."'");
  113. }
  114. $this->$field = $args[0];
  115. $this->completeOwningSide($field, $targetClass, $args[0]);
  116. } else {
  117. throw new \BadMethodCallException("no field with name '".$field."' exists on '".$this->cm->getName()."'");
  118. }
  119. }
  120. /**
  121. * Get persistent field value.
  122. *
  123. * @throws BadMethodCallException - When no persistent field exists by that name.
  124. * @param string $field
  125. * @return mixed
  126. */
  127. private function get($field)
  128. {
  129. $this->initializeDoctrine();
  130. if ( $this->cm->hasField($field) || $this->cm->hasAssociation($field) ) {
  131. return $this->$field;
  132. } else {
  133. throw new \BadMethodCallException("no field with name '".$field."' exists on '".$this->cm->getName()."'");
  134. }
  135. }
  136. /**
  137. * If this is an inverse side association complete the owning side.
  138. *
  139. * @param string $field
  140. * @param ClassMetadata $targetClass
  141. * @param object $targetObject
  142. */
  143. private function completeOwningSide($field, $targetClass, $targetObject)
  144. {
  145. // add this object on the owning side aswell, for obvious infinite recursion
  146. // reasons this is only done when called on the inverse side.
  147. if ($this->cm->isAssociationInverseSide($field)) {
  148. $mappedByField = $this->cm->getAssociationMappedByTargetField($field);
  149. $targetMetadata = self::$objectManager->getClassMetadata($targetClass);
  150. $setter = ($targetMetadata->isCollectionValuedAssociation($mappedByField) ? "add" : "set").$mappedByField;
  151. $targetObject->$setter($this);
  152. }
  153. }
  154. /**
  155. * Add an object to a collection
  156. *
  157. * @param type $field
  158. * @param assoc $args
  159. */
  160. private function add($field, $args)
  161. {
  162. $this->initializeDoctrine();
  163. if ($this->cm->hasAssociation($field) && $this->cm->isCollectionValuedAssociation($field)) {
  164. $targetClass = $this->cm->getAssociationTargetClass($field);
  165. if (!($args[0] instanceof $targetClass)) {
  166. throw new \InvalidArgumentException("Expected persistent object of type '".$targetClass."'");
  167. }
  168. if (!($this->$field instanceof Collection)) {
  169. $this->$field = new ArrayCollection($this->$field ?: array());
  170. }
  171. $this->$field->add($args[0]);
  172. $this->completeOwningSide($field, $targetClass, $args[0]);
  173. } else {
  174. throw new \BadMethodCallException("There is no method add".$field."() on ".$this->cm->getName());
  175. }
  176. }
  177. /**
  178. * Initialize Doctrine Metadata for this class.
  179. *
  180. * @return void
  181. */
  182. private function initializeDoctrine()
  183. {
  184. if ($this->cm !== null) {
  185. return;
  186. }
  187. if (!self::$objectManager) {
  188. throw new \RuntimeException("No runtime object manager set. Call PersistentObject#setObjectManager().");
  189. }
  190. $this->cm = self::$objectManager->getClassMetadata(get_class($this));
  191. }
  192. /**
  193. * Magic method that implements
  194. *
  195. * @param string $method
  196. * @param array $args
  197. * @return mixed
  198. */
  199. public function __call($method, $args)
  200. {
  201. $command = substr($method, 0, 3);
  202. $field = lcfirst(substr($method, 3));
  203. if ($command == "set") {
  204. $this->set($field, $args);
  205. } else if ($command == "get") {
  206. return $this->get($field);
  207. } else if ($command == "add") {
  208. $this->add($field, $args);
  209. } else {
  210. throw new \BadMethodCallException("There is no method ".$method." on ".$this->cm->getName());
  211. }
  212. }
  213. }