我创建了一个订户(用于任何更新,创建或更新事件)以创建日志系统(日志是一个实体,在我的应用程序中具有所有事件的记录),但是我遇到了一个问题:当我进行冲洗时,冲洗超过了执行时间。
class EntitySubscriber implements EventSubscriber
{
public function __construct(TokenStorageInterface $tokenStorage)
{
$this->tokenStorage = $tokenStorage;
}
/**
* Returns an array of events this subscriber wants to listen to.
*
* @return array
*/
public function getSubscribedEvents()
{
return array(
'postPersist',
'postUpdate',
'postRemove'
);
}
public function postUpdate(LifecycleEventArgs $args)
{
$this->save($args, 'update');
}
public function postPersist(LifecycleEventArgs $args)
{
$this->save($args, 'create');
}
public function postRemove(LifecycleEventArgs $args)
{
$this->save($args, 'delete');
}
private function save($args, $type)
{
$entity = $args->getEntity();
$entityManager = $args->getEntityManager();
$event = '';
if ($entity instanceof User) {
$changeArray = $args->getEntityManager()->getUnitOfWork()->getEntityChangeSet($args->getObject());
if(array_key_exists('lastLogin', $changeArray))
$event = $entity->getUsername(). ' has been authenticated';
elseif($type == 'update')
$event = 'User '.$entity->getUsername(). ' has been updated';
elseif ($type == 'create')
$event = 'User '.$entity->getUsername(). ' has been created';
elseif ($type == 'delete')
$event = $entity->getUsername(). ' has been deleted';
}
// check if the user successfully authenticated
if ($token = $this->tokenStorage->getToken())
if (($user = $token->getUser()) instanceof User){
$userLog = new UserLog();
$userLog->setUser($user);
$userLog->setEvent($event);
$userLog->setType($type);
$entityManager->persist($userLog);
$entityManager->flush();
}
}
}
答案 0 :(得分:0)
通过从此事件订阅者下调用flush()
,您正在进入一个无限循环。这就是导致您的请求超时的原因。
您还为UserLog实体执行了// check if the user successfully authenticated
,因为您没有检查$entity type
。
因此解决方案是:
1)删除该flush()调用,因为那里根本不需要它
2)添加可跳过UserLog实体的save()
操作的支票
private function save($args, $type){
$entity = $args->getEntity();
//Prevent logging the UserLog entity operations to avoid endless loop
if($entity instanceof UserLog) return;
...
}