graphaware/neo4j-php-ogm event listeners

268 Views Asked by At

I recently created a new symfony project (3.1) with a dependency on graphaware/neo4j-php-ogm and neo4j/neo4j-bundle to manage my database.

Then I created a new Entity class named User with properties (login, password, ...) and I want to automatically set the current date before the flush event occurs (on preFlush). I saw the PRE_FLUSH constant in neo4j-php-ogm/src/Events.php (https://github.com/graphaware/neo4j-php-ogm/blob/master/src/Events.php) but I haven't found any information about it in the documentation.

Well, my question is : Can we use this functionality in the actual version of the OGM ? If yes, do you have an example of the usage ?

Thank you for your help !

2

There are 2 best solutions below

2
On BEST ANSWER

Yes you can, it is not documented you are right, I'll make sure it will be soon.

Integration test here : https://github.com/graphaware/neo4j-php-ogm/blob/master/tests/Integration/EventListenerIntegrationTest.php

First, You need create a class that will act as EventListener to the preFlush event of the EntityManager and a method reacting to the event :

<?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);
            }
        }
    }
}

Then you can register this event listener after having creating the entity manager :

/**
     * @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());
    }

Result of the test :

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)

Result in the database :

enter image description here

0
On

Thank you a lot ! It's work perfectly. If anyone want to use it don't forget to type your property as "int". ;)