postPersist被称为无限次Symfony2

时间:2016-10-26 04:37:16

标签: mongodb symfony

我想为我的项目中的每个文档创建已删除,创建,更新等文档的日志,以便我可以在将来跟踪谁为应用程序中的特定文档(表格)做了什么。

我创建了以下服务:

名称空间/ BUNDLENAME /资源/配置/ services.xml中

 <service id="edu.account.event.listener1" class="Namespace\BundleName\EventListener\postPersistListener">
        <argument type="service" id="session"/>
        <argument type="service" id="router"/>
        <tag name="doctrine_mongodb.odm.event_listener" event = "postPersist" method="postPersist"/>
 </service>

我的听众是:

class postPersistListener
{
    private $session;
    private $router;
    private $commonFunctions;
    private $constants;

    public function __construct(Session $session, Router $router)
    {
        $this->session = $session;
        $this->router = $router;
        $this->commonFunctions = new CommonFunctions();
        $this->constants = new allConstants();
    }

//Always fire when any Add/Update/Delete operations will occurs in any documents in account module
    public function postPersist(LifecycleEventArgs $args)
    {
        $this->createLog($args);
    }

    public function createLog(LifecycleEventArgs $eventArgs)
    {
        $userID = $this->session->get('userid');
        $event = "CREATED";
        $document = $eventArgs->getDocument()->getId();
        $this->dm = $eventArgs->getDocumentManager();
        $md = $this->dm->getClassMetadata(get_class($eventArgs->getDocument()));
        $documentName = $md->getcollection();

        $this->commonFunctions->createActivityLog($this->dm, $document, $documentName, $event, $userID);

        return true;
    }
}

函数createActivityLog()在另一个文件中定义为:

public function createActivityLog($dm, $documentId, $documentName, $event, $userId)
{
    $systemIp = $_SERVER['REMOTE_ADDR'];
    $computerName = gethostbyaddr($systemIp);

    $documentActivity = new ActivityLogs();

    $documentActivity->setDocumentName($documentName);
    $documentActivity->setEvent($event);
    $documentActivity->setObjectId($documentId);
    $documentActivity->setOnDate(time());
    $documentActivity->setUserId($userId);
    $documentActivity->setComputerIp($systemIp);
    $documentActivity->setHostName($computerName);
    $dm->persist($documentActivity);
    $dm->flush();
}

所以现在当我创建文档时,它会被执行无限次。它在Document:&#34; ActivityLogs&#34;中插入大约30000个条目。相反,它应该在&#34; ActivityLogs&#34;中插入一个条目。记录表。

0 个答案:

没有答案