Trigger by Listener Example
Posted: Mon Jan 25, 2021 5:16 am
1) project/src/EventSubscriber/PlayerFiveCListener.php
Listener if data insert
Be-care to check and skip if no related to Entity
Listener if data was update on specific columns by $eventArgs
Action function on Listener to update to db by $entityManager
2) project/config/services.yaml add config lines for PlayerFiveCListener
Code: Select all
<?php
namespace App\EventSubscriber;
use Doctrine\ORM\Event\LifecycleEventArgs;
use App\Entity\FiveC;
use App\Entity\User;
use App\Entity\PlayerChallenge;
class PlayerFiveCListener
{
...
}
Listener if data insert
Code: Select all
public function postPersist(LifecycleEventArgs $args)
{
$entity = $args->getEntity();
if (!$entity instanceof FiveC) {
return;
}
$entityManager = $args->getObjectManager();
$this->updatePlayerActualPoint($entity, $entityManager);
}
Code: Select all
if (!$entity instanceof FiveC) {
return;
}
Listener if data was update on specific columns by $eventArgs
Code: Select all
public function postUpdate(LifecycleEventArgs $args)
{
$entity = $args->getEntity();
if (!$entity instanceof FiveC) {
return;
}
$entityManager = $args->getObjectManager();
// Get change set fields with old[0] and update[1] data
$eventArgs = $args->getEntityManager()->getUnitOfWork()->getEntityChangeSet($entity);
$existChangePCRI = isset( $eventArgs['pcri'] ) && !empty( $eventArgs['pcri'][1] );
$existChangeCREA = isset( $eventArgs['crea'] ) && !empty( $eventArgs['crea'][1] );
$existChangeCOOM = isset( $eventArgs['comm'] ) && !empty( $eventArgs['comm'][1] );
$existChangeCOLL = isset( $eventArgs['coll'] ) && !empty( $eventArgs['coll'][1] );
$existChangeCOES = isset( $eventArgs['coes'] ) && !empty( $eventArgs['coes'][1] );
if ($eventArgs->getEntity() instanceof FiveC) {
if ( ($existChangePCRI || $existChangeCREA || $existChangeCOOM || $existChangeCOLL || $existChangeCOES)) {
$this->updatePlayerActualPoint($entity, $entityManager);
}
}
}
Action function on Listener to update to db by $entityManager
Code: Select all
protected function updatePlayerActualPoint($entity, $entityManager){
$player = $entity->getPlayer();
$actual_skill_points = $entityManager->getRepository(PlayerChallenge::class)->calculatePlayerActuallPoint($player);
$player->setPlayerActualPoints($actual_skill_points);
$entityManager->flush();
}
2) project/config/services.yaml add config lines for PlayerFiveCListener
Code: Select all
services:
app_api.event.player_fiveC_listener:
class: App\EventSubscriber\PlayerFiveCListener
tags:
- { name: doctrine.event_listener, event: postPersist, priority: 10 }
- { name: doctrine.event_listener, event: postUpdate, priority: 10 }