[英]Doctrine 2 - Log changes in manyToMany relation
我使用Loggable行為擴展來記錄我的實體中的更改。 我想記錄manyToMany關系中的更改。 我想向用戶顯示這種更改日志:
+--------------------------------------------------+
| Article "My Article" change log: |
+-------+------------+-----------------------------+
| Who | When | What |
+-------+------------+-----------------------------+
| Admin | 2015-07-01 | Removed tags "tag1", "tag2" |
| Admin | 2015-07-01 | Added tags "tag3" |
+-------+------------+-----------------------------+
我認為, 當manyToMany關系發生變化時 , Doctrine不會觸發事件 ,因此Loggable(監聽學說事件)不會保存日志條目。 我可以通過創建自己的manyToMany表來解決它,但這是第二個問題:
當我在沒有@JoinTable注釋的情況下創建表示manyToMany關系的實體時,我不知道如何編寫新實體以像舊的JoinTable一樣。 我不希望BC休息。 你能給我一個線索,Doctrine如何處理這個問題?
您有什么建議,如何記錄manyToMany關系中的變化?
無需創建自己的連接表的解決方案。
我已經修改了我創建的LoggableListener來覆蓋Gedmo LoggableListener,我的版本可以工作,玩這個直到你讓它工作。
基本上,使用您自己的版本擴展Gedmo LoggableListener並覆蓋/添加一些修改的函數:
啟用prePersistLogEntry以允許您根據需要修改logEntry。 我的logEntry實體包含用戶實體和用戶全名而不是用戶名。
getCollectionsChangeSetData是一個新函數,用於提取集合並訪問Doctrine PersistentCollections方法。 [ http://www.doctrine-project.org/api/orm/2.1/class-Doctrine.ORM.PersistentCollection.html]
stripCollectionArray用於從集合實體中提取所需信息的新函數,並將它們插入到php數組中以持久保存到LogEntry。
有關信息,如果您計划使用Loggable doctrine擴展的還原功能,那么您還需要擴展和覆蓋LogEntryRepository中的revert方法。 當前的revert方法無法識別LogEntry中保存的ManyToMany關聯中的id。 這就是為什么stripCollectionArray函數還將'id'和'class'值保存到LogEntry。
祝好運。
<?php
namespace AppBundle\Listener;
use Doctrine\Common\EventArgs;
use Gedmo\Loggable\Mapping\Event\LoggableAdapter;
use Gedmo\Tool\Wrapper\AbstractWrapper;
use Gedmo\Loggable\LoggableListener as GedmoLoggableListener;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
use AppBundle\Entity\Clause;
use AppBundle\Entity\GuidanceNote;
use AppBundle\Entity\Standard;
use Gedmo\Loggable\Entity\MappedSuperclass\AbstractLogEntry;
use Doctrine\ORM\PersistentCollection;
/**
* Loggable listener
*
* Extends the Gedmo loggable listener to provide some custom functionality.
*
*
* @author Mark Ogilvie <mark.ogilvie@specshaper.com>
*/
class LoggableListener extends GedmoLoggableListener {
// Token storage to get user
private $tokenStorage;
// Injet token storage in the services.yml
public function __construct(TokenStorageInterface $token) {
$this->tokenStorage = $token;
}
/**
* Manipulate the LogEntry entity prior to persisting.
* In this case add a user, and set entity information
* according to the custom entity family group.
*
* @param EventArgs $eventArgs
*
* @return void
*/
protected function prePersistLogEntry($logEntry, $object) {
$user = $this->tokenStorage->getToken()->getUser();
$logEntry instanceof AbstractLogEntry;
$logEntry
->setUser($user)
->setChangedObject('text.default')
->setUsername($user->getFullName())
;
switch (true) {
case $object instanceof Clause:
$logEntry->setChangedObject('text.clause')
->setEntity($object)
;
break;
case $object instanceof GuidanceNote:
$logEntry->setChangedObject('text.guidanceNote')
->setEntity($object->getClause())
;
break;
case $object instanceof Standard:
$logEntry->setChangedObject('text.standard')
;
break;
}
}
/**
* Returns an objects changeset data
*
* Modified to create an array which has old and new values instead
* of just the new.
*
* Also added reference to UoW collection changes to pick up ManyToMany
* relationships
*
* @param LoggableAdapter $ea
* @param object $object
* @param object $logEntry
*
* @return array
*/
protected function getObjectChangeSetData($ea, $object, $logEntry) {
$om = $ea->getObjectManager();
$wrapped = AbstractWrapper::wrap($object, $om);
$meta = $wrapped->getMetadata();
$config = $this->getConfiguration($om, $meta->name);
$uow = $om->getUnitOfWork();
// Define an array to return as the change set data.
$returnArray = array();
foreach ($ea->getObjectChangeSet($uow, $object) as $field => $changes) {
if (empty($config['versioned']) || !in_array($field, $config['versioned'])) {
continue;
}
$value = $changes[1];
if ($meta->isSingleValuedAssociation($field) && $value) {
if ($wrapped->isEmbeddedAssociation($field)) {
$value = $this->getObjectChangeSetData($ea, $value, $logEntry);
} else {
$oid = spl_object_hash($value);
$wrappedAssoc = AbstractWrapper::wrap($value, $om);
$value = $wrappedAssoc->getIdentifier(false);
if (!is_array($value) && !$value) {
$this->pendingRelatedObjects[$oid][] = array(
'log' => $logEntry,
'field' => $field,
);
}
}
}
$returnArray[$field]['previous'] = $changes[0];
$returnArray[$field]['new'] = $value;
}
// For each collection add it to the return array in our custom format.
foreach ($uow->getScheduledCollectionUpdates() as $col) {
$associations = $this->getCollectionChangeSetData($col);
$returnArray = array_merge($returnArray, $associations);
}
return $returnArray;
}
/**
* New custom function to get information about changes to entity relationships
* Use the PersistentCollection methods to extract the info you want.
*
* @param PersistentCollection $col
* @return array
*/
private function getCollectionChangeSetData(PersistentCollection $col) {
$fieldName = $col->getMapping()['fieldName'];
// http://www.doctrine-project.org/api/orm/2.1/class-Doctrine.ORM.PersistentCollection.html
// $col->toArray() returns the onFlush array of collection items;
// $col->getSnapshot() returns the prePersist array of collection items
// $col->getDeleteDiff() returns the deleted items
// $col->getInsertDiff() returns the inserted items
// These methods return persistentcollections. You need to process them to get just the title/name
// of the entity you want.
// Instead of creating two records, you can create an array of added and removed fields.
// Use private a newfunction stripCollectionArray to process the entity into the array
$newValues[$fieldName]['new'] = $this->stripCollectionArray($col->toArray());
$newValues[$fieldName]['previous'] = $this->stripCollectionArray($col->getSnapshot());
return $newValues;
}
/**
* Function to process your entity into the desired format for inserting
* into the LogEntry
*
* @param type $entityArray
* @return type
*/
private function stripCollectionArray($entityArray) {
$returnArr = [];
foreach ($entityArray as $entity) {
$arr = [];
$arr['id'] = $entity->getId();
$arr['class'] = get_class($entity);
if (method_exists($entity, 'getName')) {
$arr['name'] = $entity->getName();
} elseif (method_exists($entity, 'getTitle')) {
$arr['name'] = $entity->getTitle();
} else {
$arr['name'] = get_class($entity);
}
$returnArr[] = $arr;
}
return $returnArr;
}
}
由於我無法在接受的答案中添加評論,我會在這里寫:)
如果您的主實體在同一次刷新中有多個持久性,則接受的解決方案將不起作用。 最后一組ManyToMany集合將附加到所有持久化實體。 如果您只想選擇approriate,則必須檢查該集合是否屬於已處理對象。
例如,而不是
// For each collection add it to the return array in our custom format.
foreach ($uow->getScheduledCollectionUpdates() as $col) {
$associations = $this->getCollectionChangeSetData($col);
$returnArray = array_merge($returnArray, $associations);
}
您可以使用
// For each collection add it to the return array in our custom format.
$objectHash = spl_object_hash($object);
foreach ($uow->getScheduledCollectionUpdates() as $col) {
$collectionOwner = $col->getOwner();
if (spl_object_hash($collectionOwner) === $objectHash) {
$associations = $this->getCollectionChangeSetData($col);
$returnArray = array_merge($returnArray, $associations);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.