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\Persistence\Mapping\ClassMetadata;
23 use Doctrine\Common\Collections\ArrayCollection;
24 use Doctrine\Common\Collections\Collection;
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.
35 * 1. All persistent objects have to be associated with a single ObjectManager, multiple
36 * ObjectManagers are not supported. You can set the ObjectManager with `PersistentObject#setObjectManager()`.
37 * 2. Setters and getters only work if a ClassMetadata instance was injected into the PersistentObject.
38 * This is either done on `postLoad` of an object or by accessing the global object manager.
39 * 3. There are no hooks for setters/getters. Just implement the method yourself instead of relying on __call().
40 * 4. Slower than handcoded implementations: An average of 7 method calls per access to a field and 11 for an association.
41 * 5. Only the inverse side associations get autoset on the owning side aswell. Setting objects on the owning side
42 * will not set the inverse side associations.
46 * PersistentObject::setObjectManager($em);
48 * class Foo extends PersistentObject
54 * $foo->getId(); // method exists through __call
56 * @author Benjamin Eberlei <kontakt@beberlei.de>
58 abstract class PersistentObject implements ObjectManagerAware
63 private static $objectManager;
71 * Set the object manager responsible for all persistent object base classes.
73 * @param ObjectManager $objectManager
75 static public function setObjectManager(ObjectManager $objectManager = null)
77 self::$objectManager = $objectManager;
81 * @return ObjectManager
83 static public function getObjectManager()
85 return self::$objectManager;
89 * Inject Doctrine Object Manager
91 * @param ObjectManager $objectManager
92 * @param ClassMetadata $classMetadata
94 * @throws \RuntimeException
96 public function injectObjectManager(ObjectManager $objectManager, ClassMetadata $classMetadata)
98 if ($objectManager !== self::$objectManager) {
99 throw new \RuntimeException("Trying to use PersistentObject with different ObjectManager instances. " .
100 "Was PersistentObject::setObjectManager() called?");
103 $this->cm = $classMetadata;
107 * Sets a persistent fields value.
109 * @param string $field
112 * @throws \BadMethodCallException - When no persistent field exists by that name.
113 * @throws \InvalidArgumentException - When the wrong target object type is passed to an association
116 private function set($field, $args)
118 $this->initializeDoctrine();
120 if ($this->cm->hasField($field) && !$this->cm->isIdentifier($field)) {
121 $this->$field = $args[0];
122 } else if ($this->cm->hasAssociation($field) && $this->cm->isSingleValuedAssociation($field)) {
123 $targetClass = $this->cm->getAssociationTargetClass($field);
124 if (!($args[0] instanceof $targetClass) && $args[0] !== null) {
125 throw new \InvalidArgumentException("Expected persistent object of type '".$targetClass."'");
127 $this->$field = $args[0];
128 $this->completeOwningSide($field, $targetClass, $args[0]);
130 throw new \BadMethodCallException("no field with name '".$field."' exists on '".$this->cm->getName()."'");
135 * Get persistent field value.
138 * @param string $field
140 * @throws \BadMethodCallException - When no persistent field exists by that name.
143 private function get($field)
145 $this->initializeDoctrine();
147 if ( $this->cm->hasField($field) || $this->cm->hasAssociation($field) ) {
148 return $this->$field;
150 throw new \BadMethodCallException("no field with name '".$field."' exists on '".$this->cm->getName()."'");
155 * If this is an inverse side association complete the owning side.
157 * @param string $field
158 * @param ClassMetadata $targetClass
159 * @param object $targetObject
161 private function completeOwningSide($field, $targetClass, $targetObject)
163 // add this object on the owning side aswell, for obvious infinite recursion
164 // reasons this is only done when called on the inverse side.
165 if ($this->cm->isAssociationInverseSide($field)) {
166 $mappedByField = $this->cm->getAssociationMappedByTargetField($field);
167 $targetMetadata = self::$objectManager->getClassMetadata($targetClass);
169 $setter = ($targetMetadata->isCollectionValuedAssociation($mappedByField) ? "add" : "set").$mappedByField;
170 $targetObject->$setter($this);
175 * Add an object to a collection
177 * @param string $field
180 * @throws \BadMethodCallException
181 * @throws \InvalidArgumentException
183 private function add($field, $args)
185 $this->initializeDoctrine();
187 if ($this->cm->hasAssociation($field) && $this->cm->isCollectionValuedAssociation($field)) {
188 $targetClass = $this->cm->getAssociationTargetClass($field);
189 if (!($args[0] instanceof $targetClass)) {
190 throw new \InvalidArgumentException("Expected persistent object of type '".$targetClass."'");
192 if (!($this->$field instanceof Collection)) {
193 $this->$field = new ArrayCollection($this->$field ?: array());
195 $this->$field->add($args[0]);
196 $this->completeOwningSide($field, $targetClass, $args[0]);
198 throw new \BadMethodCallException("There is no method add".$field."() on ".$this->cm->getName());
203 * Initialize Doctrine Metadata for this class.
205 * @throws \RuntimeException
208 private function initializeDoctrine()
210 if ($this->cm !== null) {
214 if (!self::$objectManager) {
215 throw new \RuntimeException("No runtime object manager set. Call PersistentObject#setObjectManager().");
218 $this->cm = self::$objectManager->getClassMetadata(get_class($this));
222 * Magic method that implements
224 * @param string $method
227 * @throws \BadMethodCallException
230 public function __call($method, $args)
232 $command = substr($method, 0, 3);
233 $field = lcfirst(substr($method, 3));
234 if ($command == "set") {
235 $this->set($field, $args);
236 } else if ($command == "get") {
237 return $this->get($field);
238 } else if ($command == "add") {
239 $this->add($field, $args);
241 throw new \BadMethodCallException("There is no method ".$method." on ".$this->cm->getName());