symfony - graphaware/neo4j-php-ogm 事件监听器

标签 symfony neo4j graphaware neo4j-php-ogm

我最近创建了一个新的 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 的实际版本中使用此功能吗?如果是,您有使用示例吗?

感谢您的帮助!

最佳答案

是的,你可以,没有记录,你是对的,我会确保很快就会有记录。

此处集成测试:https://github.com/graphaware/neo4j-php-ogm/blob/master/tests/Integration/EventListenerIntegrationTest.php

首先,您需要创建一个类,该类将充当 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)

数据库中的结果:

enter image description here

关于symfony - graphaware/neo4j-php-ogm 事件监听器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42138492/

相关文章:

php - Symfony 3.0.1 CSRF token 存在但无效

php - 奏鸣曲管理员无法获得翻译以使用 sortable

php - 通知: unserialize(): Error at offset | data trimmed in MySQL

php - Neo4j 只找到 10 部电影

java - 将 GraphAware 友谊计数器示例部署到一些独立的 Neo4j 服务器

php - CompilerPass 的 Symfony2 解释?

neo4j - 如何在 Cypher 中复制节点并在原始节点上设置值

java - 执行引擎不打印结果

spring - 使用 Spring Data Neo4j 的简单对象/图形映射获取事务的正确方法?

elasticsearch - 如何标记从 Neo4j 复制到 Elastic 搜索的数据?