Is there a rollback event from Doctrine? those. do things for entities in the changelog where there is a rollback
Working with Doctrine on Symfony 2.6 is there a way to "detect" transaction rollbacks for objects that have been saved?
my original problem . I am creating new objects that represent files on the filesystem. On $em->persist()
these entities, files are moved from the directory /temp
to the final deintegration vĂa Doctrine PrePersist. If the transaction I'm working on rolls back later in the code, no rows are created in the database, but the files are delayed and I have to manually delete them afterward $em->rollback()
with additional code, every time I do this. Thus, I can tell that there might be an event that I can use to detect an object that has been "removed" from the changelog or "rolled back", so I can delete the file associated with the entity.
also : PostPersist or PostFlush event seems to solve my problem, but if I have multiple instructions $em->flush()
and one of them below in code throws an exception and I do $em->rollback()
on the whole transaction I still get lingering files
source to share
There is no rollback event by default in Doctrine. But what you can do is extend the Connection class and create your own event:
<?php
namespace Acme\MyBundle\Doctrine\DBAL;
use Doctrine\DBAL\Connection;
use Ozean12\ApiSDKBundle\Doctrine\Event\PostCommitEventArgs;
use Ozean12\ApiSDKBundle\Doctrine\Event\PostRollbackEventArgs;
/**
* Class ConnectionWrapper
*/
class ConnectionWrapper extends Connection
{
/**
* {@inheritdoc}
*/
public function commit()
{
parent::commit();
if (!$this->isTransactionActive()) { // to be sure that we are committing a top-level transaction
$this->getEventManager()->dispatchEvent(PostCommitEventArgs::NAME, new PostCommitEventArgs());
}
}
/**
* {@inheritdoc}
*/
public function rollBack()
{
parent::rollBack();
if (!$this->isTransactionActive()) { // to be sure that we are rolling-back a top-level transaction
$this->getEventManager()->dispatchEvent(PostRollbackEventArgs::NAME, new PostRollbackEventArgs());
}
}
}
Then declare this class as a connection wrapper:
doctrine:
dbal:
wrapper_class: Acme\MyBundle\Doctrine\DBAL\ConnectionWrapper
And create event and subscriber classes. You can keep track of persistent objects in the same subscriber class by listening for the onFlush event so you can take action on them when a commit or rollback occurs.
source to share
Use an EntityManager connection to start a transaction and then do your work with the db through Doctrine and either commit on success or rollback as you fail.
$conn = $entityManager->getConnection();
$conn->beginTransaction();
/*
Your work here
*/
// if success
$conn->commit();
// else failure
$conn->rollback();
source to share