/** * Saves the objects, and executes the supplied callback, wrapping in a try / catch and transaction. * This meant to be used to save associated relationships when overriding the the saveAll() method. * * Functions will receive an array parameter with the objects that have just been saved * * @param DataObjectInterface[] $objects * @param callable $afterSave * @param callable $exceptionHandler */ protected function saveAllWith(array $objects, callable $afterSave, callable $exceptionHandler = null) { $this->objectMapper->unitOfWork()->executeTransaction(function () use($objects, $afterSave) { self::saveAll($objects); $afterSave($objects); }, $exceptionHandler); }
/** * Saves relationship data to a link table containing the id's of both objects. * * This method inserts / updates the foreign objects. * Missing foreign objects will be removed from the link table, but not deleted. * * @param DataObjectInterface[] $objects * @param string $className Class name of foreign objects to load * @param string $linkTable Table that links two objects together * @param string $foreignObjectGetter Name of getter to retrieve foreign objects * @param string $idColumn Column on link table = the id on this object * @param string $foreignIdColumn Column on link table = the id on the foreign object table */ public function saveManyToMany(array $objects, $className, $linkTable, $foreignObjectGetter = null, $idColumn = null, $foreignIdColumn = null) { if (empty($objects)) { return; } if (!$foreignObjectGetter) { $foreignObjectGetter = 'get' . $this->inflector->methodNameFromClass($className, true); } $foreignObjectsToSave = []; foreach ($objects as $object) { if (!method_exists($object, $foreignObjectGetter)) { throw new MethodNotImplementedException("{$foreignObjectGetter} must be defined on {$object->getClassName()} to save relationship"); } /** @var DataObjectInterface[] $foreignObjects */ $foreignObjects = $object->{$foreignObjectGetter}(); if (!empty($foreignObjects)) { if (!is_array($foreignObjects)) { throw new MethodNotImplementedException("{$foreignObjectGetter} on {$object->getClassName()} must return an array to save relationship"); } foreach ($foreignObjects as $foreignObject) { $foreignObjectsToSave[] = $foreignObject; } } } $this->objectMapper->unitOfWork()->executeTransaction(function () use($foreignObjectsToSave, $objects, $className, $linkTable, $foreignObjectGetter, $idColumn, $foreignIdColumn) { $this->objectMapper->saveAll($foreignObjectsToSave); $this->saveManyToManyLinks($objects, $className, $linkTable, $foreignObjectGetter, $idColumn, $foreignIdColumn); }); }