2017-02-09 72 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”。 ;)