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.
15 * This software consists of voluntary contributions made by many individuals
16 * and is licensed under the MIT license. For more information, see
17 * <http://www.doctrine-project.org>.
20 namespace Doctrine\Common\Persistence;
22 use Doctrine\Common\Collections\ArrayCollection;
23 use Doctrine\Common\Collections\Collection;
24 use Doctrine\Common\Persistence\Mapping\ClassMetadata;
27 * PersistentObject base class that implements getter/setter methods for all mapped fields and associations
28 * by overriding __call.
30 * This class is a forward compatible implementation of the PersistentObject trait.
34 * 1. All persistent objects have to be associated with a single ObjectManager, multiple
35 * ObjectManagers are not supported. You can set the ObjectManager with `PersistentObject#setObjectManager()`.
36 * 2. Setters and getters only work if a ClassMetadata instance was injected into the PersistentObject.
37 * This is either done on `postLoad` of an object or by accessing the global object manager.
38 * 3. There are no hooks for setters/getters. Just implement the method yourself instead of relying on __call().
39 * 4. Slower than handcoded implementations: An average of 7 method calls per access to a field and 11 for an association.
40 * 5. Only the inverse side associations get autoset on the owning side as well. Setting objects on the owning side
41 * will not set the inverse side associations.
45 * PersistentObject::setObjectManager($em);
47 * class Foo extends PersistentObject
53 * $foo->getId(); // method exists through __call
55 * @author Benjamin Eberlei <kontakt@beberlei.de>
57 abstract class PersistentObject implements ObjectManagerAware
60 * @var ObjectManager|null
62 private static $objectManager = null;
65 * @var ClassMetadata|null
70 * Sets the object manager responsible for all persistent object base classes.
72 * @param ObjectManager|null $objectManager
76 static public function setObjectManager(ObjectManager $objectManager = null)
78 self::$objectManager = $objectManager;
82 * @return ObjectManager|null
84 static public function getObjectManager()
86 return self::$objectManager;
90 * Injects the Doctrine Object Manager.
92 * @param ObjectManager $objectManager
93 * @param ClassMetadata $classMetadata
97 * @throws \RuntimeException
99 public function injectObjectManager(ObjectManager $objectManager, ClassMetadata $classMetadata)
101 if ($objectManager !== self::$objectManager) {
102 throw new \RuntimeException("Trying to use PersistentObject with different ObjectManager instances. " .
103 "Was PersistentObject::setObjectManager() called?");
106 $this->cm = $classMetadata;
110 * Sets a persistent fields value.
112 * @param string $field
117 * @throws \BadMethodCallException When no persistent field exists by that name.
118 * @throws \InvalidArgumentException When the wrong target object type is passed to an association.
120 private function set($field, $args)
122 if ($this->cm->hasField($field) && !$this->cm->isIdentifier($field)) {
123 $this->$field = $args[0];
124 } else if ($this->cm->hasAssociation($field) && $this->cm->isSingleValuedAssociation($field)) {
125 $targetClass = $this->cm->getAssociationTargetClass($field);
126 if (!($args[0] instanceof $targetClass) && $args[0] !== null) {
127 throw new \InvalidArgumentException("Expected persistent object of type '".$targetClass."'");
129 $this->$field = $args[0];
130 $this->completeOwningSide($field, $targetClass, $args[0]);
132 throw new \BadMethodCallException("no field with name '".$field."' exists on '".$this->cm->getName()."'");
137 * Gets a persistent field value.
139 * @param string $field
143 * @throws \BadMethodCallException When no persistent field exists by that name.
145 private function get($field)
147 if ( $this->cm->hasField($field) || $this->cm->hasAssociation($field) ) {
148 return $this->$field;
151 throw new \BadMethodCallException("no field with name '".$field."' exists on '".$this->cm->getName()."'");
155 * If this is an inverse side association, completes the owning side.
157 * @param string $field
158 * @param ClassMetadata $targetClass
159 * @param object $targetObject
163 private function completeOwningSide($field, $targetClass, $targetObject)
165 // add this object on the owning side as well, for obvious infinite recursion
166 // reasons this is only done when called on the inverse side.
167 if ($this->cm->isAssociationInverseSide($field)) {
168 $mappedByField = $this->cm->getAssociationMappedByTargetField($field);
169 $targetMetadata = self::$objectManager->getClassMetadata($targetClass);
171 $setter = ($targetMetadata->isCollectionValuedAssociation($mappedByField) ? "add" : "set").$mappedByField;
172 $targetObject->$setter($this);
177 * Adds an object to a collection.
179 * @param string $field
184 * @throws \BadMethodCallException
185 * @throws \InvalidArgumentException
187 private function add($field, $args)
189 if ($this->cm->hasAssociation($field) && $this->cm->isCollectionValuedAssociation($field)) {
190 $targetClass = $this->cm->getAssociationTargetClass($field);
191 if (!($args[0] instanceof $targetClass)) {
192 throw new \InvalidArgumentException("Expected persistent object of type '".$targetClass."'");
194 if (!($this->$field instanceof Collection)) {
195 $this->$field = new ArrayCollection($this->$field ?: []);
197 $this->$field->add($args[0]);
198 $this->completeOwningSide($field, $targetClass, $args[0]);
200 throw new \BadMethodCallException("There is no method add".$field."() on ".$this->cm->getName());
205 * Initializes Doctrine Metadata for this class.
209 * @throws \RuntimeException
211 private function initializeDoctrine()
213 if ($this->cm !== null) {
217 if (!self::$objectManager) {
218 throw new \RuntimeException("No runtime object manager set. Call PersistentObject#setObjectManager().");
221 $this->cm = self::$objectManager->getClassMetadata(get_class($this));
227 * @param string $method
232 * @throws \BadMethodCallException
234 public function __call($method, $args)
236 $this->initializeDoctrine();
238 $command = substr($method, 0, 3);
239 $field = lcfirst(substr($method, 3));
240 if ($command == "set") {
241 $this->set($field, $args);
242 } else if ($command == "get") {
243 return $this->get($field);
244 } else if ($command == "add") {
245 $this->add($field, $args);
247 throw new \BadMethodCallException("There is no method ".$method." on ".$this->cm->getName());