2017-02-09 74 views
2

我最近創建了一個新的symfony項目(3.1),它依賴於graphaware/neo4j-php-ogm和neo4j/neo4j-bundle來管理我的數據庫。graphaware/neo4j-php-ogm事件監聽器

然後,我創建了一個名爲User的屬性(login,password,...)的新實體類,我想在flush事件發生前(preFlush)自動設置當前日期。 我在neo4j-php-ogm/src/Events.php(https://github.com/graphaware/neo4j-php-ogm/blob/master/src/Events.php)中看到了PRE_FLUSH常量,但我在文檔中沒有找到任何有關它的信息。

嗯,我的問題是:我們可以在實際版本的OGM中使用這個功能嗎?如果是的話,你有沒有使用的例子?

謝謝你的幫助!

回答

2

是的,你可以,它沒有記錄你是對的,我會確保它會很快。

集成測試在這裏:https://github.com/graphaware/neo4j-php-ogm/blob/master/tests/Integration/EventListenerIntegrationTest.php

首先,你需要創建一個類,將作爲事件監聽起到了EntityManager的preFlush事件和反應事件的方法:

<?php 

namespace GraphAware\Neo4j\OGM\Tests\Integration\Listeners; 

use GraphAware\Neo4j\OGM\Event\PreFlushEventArgs; 
use GraphAware\Neo4j\OGM\Tests\Integration\Model\User; 

class Timestamp 
{ 
    public function preFlush(PreFlushEventArgs $eventArgs) 
    { 
     $dt = new \DateTime("NOW", new \DateTimeZone("UTC")); 

     foreach ($eventArgs->getEntityManager()->getUnitOfWork()->getNodesScheduledForCreate() as $entity) { 
      if ($entity instanceof User) { 
       $entity->setUpdatedAt($dt); 
      } 
     } 
    } 
} 

然後你就可以在創建實體管理器後註冊此事件監聽器:

/** 
    * @group pre-flush 
    */ 
    public function testPreFlushEvent() 
    { 
     $this->clearDb(); 
     $this->em->getEventManager()->addEventListener(Events::PRE_FLUSH, new Timestamp()); 

     $user = new User("ikwattro"); 

     $this->em->persist($user); 
     $this->em->flush(); 

     $this->assertNotNull($user->getUpdatedAt()); 
     var_dump($user->getUpdatedAt()); 
    } 

測試結果:

[email protected] ~/d/g/p/ogm> ./vendor/bin/phpunit tests/ --group pre-flush 
PHPUnit 5.6.2 by Sebastian Bergmann and contributors. 

Runtime:  PHP 5.6.27 
Configuration: /Users/ikwattro/dev/graphaware/php/ogm/phpunit.xml.dist 

.                 1/1 (100%)int(1486763241) 


Time: 378 ms, Memory: 5.00MB 

OK (1 test, 1 assertion) 

導致數據庫:

enter image description here

+0

非常感謝您的幫助。我明天會試試! – Sobraz

+0

它怎麼樣,有什麼消息? –

0

謝謝你很多!這是完美的工作。如果有人想使用它,不要忘記輸入你的財產爲「int」。 ;)