我有一个用户可以创建订单的系统。创建订单后,应立即使用创建订单的当前用户,创建订单的时间以及其他一些信息更新另一个实体表。
基本上是日志。
这是我的听众课程;
namespace Qi\Bss\BaseBundle\Lib\PurchaseModule;
use Qi\Bss\BaseBundle\Entity\Business\PurchaseModule\PmodLog;
use Qi\Bss\BaseBundle\Entity\Business\PurchaseModule\PmodOrder;
use Doctrine\ORM\Event\LifecycleEventArgs;
/**
* Class OrderLogger. Purchase Module activity logger.
*/
class OrderLogger
{
/**
* Service container
* @var type
*/
private $serviceContainer;
/**
* Performs tasks before destruction
* @ORM\PostPersist
*/
public function postPersist(LifecycleEventArgs $args)
{
$order = $args->getEntity();
if ($order instanceof PmodOrder) {
$logRecord = new PmodLog();
$user = $this->serviceContainer->get('security.token_storage')->getToken()->getUser();
$logRecord->setCreatedBy($user);
$logRecord->setAction('Gemaak');
$logRecord->setCreatedAt(new \DateTime());
$logRecord->setOrder($order);
$logRecord->setDepartment($user->getDepartment());
}
}
/**
* Sets the sales order exporter object
* @param type $serviceContainer
*/
public function setServiceContainer($serviceContainer)
{
$this->serviceContainer = $serviceContainer;
}
}
我不知道我做错了什么,并且我的数据库中的日志表没有得到任何更新。
这也是我的服务;
bss.pmod.logger:
class: Qi\Bss\BaseBundle\Lib\PurchaseModule\OrderLogger
calls:
- [ setServiceContainer, [@service_container] ]
tags:
- { name: doctrine.event_listener, event: postPersist }
我没有收到错误,订单已完美创建,但日志数据库仍为空。
答案 0 :(得分:0)
您是否需要坚持和刷新 $logRecord
?您可以从$args
获得实体经理。
答案 1 :(得分:0)
您可以根据自己的需要进行调整。在某人创建User
实体后,通过从UserLog
实体插入一些数据来创建新的User
实体/记录。
<强>控制器强>
public function createAction()
{
$user = new User();
$user->setUsername('username');
$user->setPassword('password');
$this->entityManager->persist($user);
$this->entityManager->flush();
}
<强> Services.yml 强>
services:
application_backend.event_listener.user_entity:
class: Application\BackendBundle\EventListener\UserEntityListener
tags:
- { name: doctrine.event_listener, event: postPersist }
<强> UserEntityListener.php 强>
namespace Application\BackendBundle\EventListener;
use Application\BackendBundle\Entity\User;
use Application\BackendBundle\Entity\UserLog;
use Doctrine\ORM\Event\LifecycleEventArgs;
class UserEntityListener
{
public function postPersist(LifecycleEventArgs $args)
{
$entity = $args->getEntity();
if ($entity instanceof User) {
$log = new UserLog();
$log->setUserId($entity->getId());
$log->setMessage('postPersist at ' . date('d/m/Y H:i:s'));
$em = $args->getEntityManager();
$em->persist($log);
$em->flush();
}
}
}