我最近创建了一个新的 symfony 项目 (3.1),它依赖于 graphaware/neo4j-php-ogm 和 neo4j/neo4j-bundle 来管理我的数据库。
然后我创建了一个名为 User 的新实体类,其属性(登录名、密码等)我想在刷新事件发生之前(在 preFlush 上)自动设置当前日期。 我在 neo4j-php-ogm/src/Events.php ( https://github.com/graphaware/neo4j-php-ogm/blob/master/src/Events.php ) 中看到了 PRE_FLUSH 常量,但我在文档中没有找到有关它的任何信息。
嗯,我的问题是:我们可以在 OGM 的实际版本中使用此功能吗?如果是,您有使用示例吗?
感谢您的帮助!
最佳答案
是的,你可以,没有记录,你是对的,我会确保很快就会有记录。
首先,您需要创建一个类,该类将充当 EntityManager 的 preFlush
事件的 EventListener 和一个对该事件使用react的方法:
<?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());
}
测试结果:
ikwattro@graphaware-team ~/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)
数据库中的结果:
关于symfony - graphaware/neo4j-php-ogm 事件监听器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42138492/