我需要记录每个实体的更改。我有一个监听器,用于监听doctrine的事件:preRemove
、postUpdate
和postDelete
。
我的实体AccessModule
有以下关系:
App\Entity\AccessModule.php
/**
* @ORM\OneToMany(targetEntity="App\Entity\AccessModule", mappedBy="parent")
* @ORM\OrderBy({"id" = "ASC"})
*/
private $children;
/**
* @ORM\ManyToOne(targetEntity="App\Entity\AccessModule", inversedBy="children")
* @ORM\JoinColumn(name="parent_id", referencedColumnName="id", nullable=true)
*/
private $parent;
/**
* @ORM\ManyToMany(targetEntity="App\Entity\AccessModuleRoute", inversedBy="access_modules")
* @ORM\JoinTable(name="access_routes",
* joinColumns={@ORM\JoinColumn(name="access_module_id", referencedColumnName="id")},
* inverseJoinColumns={@ORM\JoinColumn(name="route_id", referencedColumnName="id")})
*
*/
private $routes;
在监听器中: App\EventListener\EntityListener.php
use Symfony\Component\Serializer\Encoder\JsonEncoder;
use Symfony\Component\Serializer\Encoder\XmlEncoder;
use Symfony\Component\Serializer\Normalizer\ObjectNormalizer;
$encoders = [new XmlEncoder(), new JsonEncoder()];
$normalizer = new ObjectNormalizer();
$normalizer->setCircularReferenceHandler(function ($object) {
return $object->getId();
});
$this->serializer = new Serializer([$normalizer], $encoders);
public function createLog(LifecycleEventArgs $args, $action){
$em = $args->getEntityManager();
$entity = $args->getEntity();
if ($this->tokenStorage->getToken()->getUser()) {
$username = $this->tokenStorage->getToken()->getUser()->getUsername();
} else {
$username = 'anon'; // TODO Remove anon. set null value
}
$log = new Log();
// $log->setData('dddd')
$log->setData($this->serializer->serialize($entity, ''json)
->setAction($action)
->setActionTime(new \DateTime())
->setUser($username)
->setEntityClass(get_class($entity));
$em->persist($log);
$em->flush();
}
我遇到了序列化的问题。当我使用
$log->setData($entity)
时,我会遇到循环引用的问题。当我使用$log->setData($this->serializer->serialize($entity, 'json'))
进行序列化时,结果会包含实体中所有关联数据,包括父级和子级,最终得到完整的树形结构:/ 我希望能够只得到...[
'id' => ID,
'name' => NAME,
'parent' => parent_id // ManyToOne, I'd like get its id
'children' => [$child_id, $child_id, $child_id] // array of $id of children array collection
]
当然,在将其编码为json之前,这只是草稿。
如何在没有完整关系的情况下获取预期数据?