2014-07-21 45 views
1

我有一個實體監聽器,如果用戶更改記錄,updatedAt字段被設置爲當前時間。如何不更新postUpdate上的字段?

然而,現在需求已經改變了,我需要運行一個腳本並一次更新所有實體,但不應該混淆用戶生成的updatedAt字段。

所以我想構建一個更新所有實體的命令,但updatedAt字段不應該更新。

我想知道如何通過這樣的參數。

此刻我想知道是否應該在實體上添加doUpdateUpdatedAt字段,並將該命令設置爲false。但我想知道是否有不同的方式。我認爲資產不應該擔心是否設置了updatedAt字段,我認爲這應該發生在我堅持實體或沖水時。

我喜歡就可能性以及它們的優點和缺點有一些反饋意見。

回答

0

偵聽器註冊,這意味着人們可以在命令中訪問它很容易在容器,並設置所需的屬性服務:

class UpdateAssetCategoryCountCommand extends AbstractCommand 
{ 
    ... 

    protected function execute(InputInterface $input, OutputInterface $output) 
    { 
     $assets = $this->findAllAssets(); 
     $em = $this->getEntityManager(); 

     $listener = $this->getContainer()->get('my.listener'); 
     $listener->doNotUpdateTimeStamp(); 

     foreach ($assets as $asset) { 
      // change the required fields 
      $em->persist($asset); 
     } 

     $em->flush(); 
    } 

在我的聽衆:

class MyListener implements EventSubscriber 
{ 
    /** 
    * @var bool 
    */ 
    private $shouldUpdateTimestamp = true; 

    ... 

    public function preUpdate(LifecycleEventArgs $arg) 
    { 
     $entity = $arg->getObject(); 
     $em = $arg->getEntityManager(); 

     if ($entity instanceof Asset) { 
      $entity->updateCategoryCount(); 
      $entity->preUploadHandlerIfFileUploaded(); 

      if ($this->shouldUpdateTimestamp) { 
       $entity->setUpdatedAt(new DateTime('now')); 
      } 

      $this->persistChanges($em, $entity); 
     } 

    public function doNotUpdateTimeStamp() 
    { 
     $this->shouldUpdateTimestamp = false; 
    } 


}