【问题标题】:Transactions for file operations in LaravelLaravel 中文件操作的事务
【发布时间】:2020-05-24 08:00:02
【问题描述】:
在 Laravel 中,我可以通过将闭包传递给 DB::transaction 函数来进行数据库事务。
Laravel 是否支持 File 或 Storage 外观的类似功能?文件操作在事务中运行的位置,在文件操作失败的情况下进行回滚?
我在想象类似的东西
$files = ... // Something that returns a collection
File::transaction(function () use ($files) {
$files->each(function() {
File::move(....);
});
});
【问题讨论】:
标签:
laravel
transactions
laravel-6
【解决方案1】:
没有内置的方法,因此您必须自己进行实现。
实现它的简单方法是
$fileName = ""; // or $fileNames ( array ) if multiple file uploads
$files = "" // to be used if you're going to update or delete files. Again if multiple file modifications then use array
try{
/* Just a note, but your new file could overwrite any existing files,
so before uploading, check if another file exists with same filename
And if it does, load that file and keep it in the $files variable
*/
// Upload File
$fileName = // name of uploaded file
$files = // Any existing file you're going to modify. Load the entire file data, not just the name
// Modify/Delete a file
}( \Exception $e ){
// Now delete the file using fileName or $fileNames if the variable is not empty
// If you modified/deleted any file, then undo those modifications using the data in $files ( if it's not empty )
}
在这种方法中,现有文件被加载到内存中,但如果有多个大文件,最好将它们移动到临时位置,如果抛出任何异常则将它们移回。如果文件事务成功,请不要忘记删除这些临时文件