原则 1.2:使用 postDelete 删除文件系统上的相关文件——具有事务支持

发布于 2024-09-30 18:25:03 字数 284 浏览 1 评论 0原文

这个问题是这个问题的一种扩展:

执行在 Symfony/Doctrine 中删除记录时进行一些清理

我正在这样做,并且工作正常,除了一个问题:如果删除失败并且事务从未提交,则 postDelete 方法仍然运行并且文件被删除反正。

避免这种情况的好方法是什么?

This question is a sort of extension to this question:

Perform some cleanup when deleting a record in Symfony/Doctrine

I'm doing this and it's working fine, except for one problem: if the delete fails and the transaction is never committed, the postDelete method still runs and the files are deleted anyway.

What would be a good way to avoid this?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

总以为 2024-10-07 18:25:03

如果您只需要在事务实际提交时触发某些操作,则需要将其在 postDelete 中排队,然后在 postTransactionCommit 处理程序中执行它,

$conn = Doctrine_Manager::connection(...);
$conn->addListener(new TransactionCommitListener());

class TransactionCommitListener extends Doctrine_EventListener {

  public function postTransactionCommit(Doctrine_Event $event) {
    if ($event->getInvoker()->getConnection()->getTransactionLevel() == 1) {
      // do your filesystem deletes here
    }
  }

  public function postTransactionRollback(Doctrine_Event $event) {
    // clear your delete queue here
  }
}

我通常使用单例来存储队列并静态获取它。如果您使用多个连接,您将需要多个队列。

上面的提交处理程序仅在最外层提交时触发,这就是 Doctrine 与 mysql 一起工作的方式,因为它不提供嵌套事务。如果您的数据库提供嵌套事务,并且学说支持这一点,您可能需要更改它。

If you need to trigger something only when the transaction has actually been committed, you need to queue it in postDelete, and then perform it in a postTransactionCommit handler

$conn = Doctrine_Manager::connection(...);
$conn->addListener(new TransactionCommitListener());

class TransactionCommitListener extends Doctrine_EventListener {

  public function postTransactionCommit(Doctrine_Event $event) {
    if ($event->getInvoker()->getConnection()->getTransactionLevel() == 1) {
      // do your filesystem deletes here
    }
  }

  public function postTransactionRollback(Doctrine_Event $event) {
    // clear your delete queue here
  }
}

I've typically used a singleton to store the queue and fetched it statically. If you are using multiple connections, you'll want to have multiple queues.

The commit handler above only fires on the outermost commit, which is how Doctrine works with mysql, since it doesn't provide nested transactions. If your database provides nested transactions, and doctrine supports that, you might need to change that.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文