Reputation: 161
I am working on an application using Symfony 3 and Twig templates. I have created forms using symfony formBuilder. I need to run a php script every time a row is inserted in database. Is there anyway that I can do this ?
Upvotes: 0
Views: 360
Reputation: 3105
First, to run a script, you can use the Process component of Symfony.
Here is an example of usage:
$phpBinaryFinder = new PhpExecutableFinder();
$phpBinaryPath = $phpBinaryFinder->find();
$process = new Process("{$phpBinaryPath} worker.php");
$process->run();
You should read the related doc for more insights.
Then you want to hook after the flush of doctrine, then use an event listener. It's a class with a specific method that you register as a service.
You need to define a class:
namespace App\EventListener;
use Doctrine\ORM\Event\PostFlushEventArgs;
use Doctrine\ORM\Event\LifecycleEventArgs;
class YourListener
{
private $persisted = [];
public function postPersist(LifecycleEventArgs $args)
{
$entity = $args->getEntity();
if (!$entity instanceof YourRecord) {
return;
}
$this->persisted[] = $entity;
}
public function postFlush(PostFlushEventArgs $args)
{
foreach ($persisted as $row) {
// Execute your action for the given row
}
}
}
Then you need to register it as service:
# services.yaml
services:
App\EventListener\YourListener:
tags:
- { name: doctrine.event_listener, event: postPersist }
- { name: doctrine.event_listener, event: postFlush }
Check the related documentation: https://symfony.com/doc/current/doctrine/event_listeners_subscribers.html
Upvotes: 1
Reputation: 659
yes of course, you can use the Events and Event Listeners https://symfony.com/doc/current/event_dispatcher.html or Doctrine Event Listeners and Subscribers https://symfony.com/doc/current/doctrine/event_listeners_subscribers.html
Upvotes: 2