Search code examples
cakephpcakephp-2.9

Remove file only on transaction commit


I've an Attachment model that stores file metadata in MySQL and actual file on file system. I've implemented deletion with Callback Methods:

public function beforeDelete($cascade = true) {
    $this->data = $this->findById($this->id);
    return parent::beforeDelete($cascade);
}

public function afterDelete() {
    $file = new File($this->data['Attachment']['path']);
    $file->delete();
}

Is there a way to determine if there's an open transaction and only perform the file system deletion if such transaction gets committed? (Transaction is of course handled in the controller, which may not even be AttachmentsCrontroller but some other.)


Solution

  • That's already a little tricky in CakePHP 3.x, where there are actual events after things have been committed, and where options objects are passed throughout the whole saving/delete process that can store information about the transaction, and even there you'd have to somehow invoke such a process yourself if you'd manually wrap a save/delete operation in a transaction.

    You could for example try to implement executing things transactionally in a behavior, your models could then store references to the files to delete in that behavior on beforeDelete, and the behavior could dispatch events on the involved models after things have been committed, something like afterCommit, which your models could listen to and then delete the files.