zenstruck / temp-file
临时文件包装器。
v1.2.1
2023-02-27 19:45 UTC
Requires
- php: >=8.0
Requires (Dev)
- phpstan/phpstan: ^1.4
- phpunit/phpunit: ^9.5.0
- symfony/phpunit-bridge: ^6.1
- symfony/service-contracts: ^1.0|^2.0|^3.0
- symfony/var-dumper: ^5.4|^6.0
README
临时文件包装器。在脚本结束时创建的文件将被删除。
安装
composer require zenstruck/temp-file
API
创建 TempFile
实例
use Zenstruck\TempFile; // create empty file with random name (in /tmp) $file = TempFile::new(); // create empty file with random filename, with extension (in /tmp) $file = TempFile::withExtension('txt'); // create file with specific filename (in /tmp) $file = TempFile::withName('my-file.txt'); // creates empty file $file = TempFile::withName('my-file.txt', 'some content'); // creates file with string content $file = TempFile::withName('my-file.txt', \fopen('some/file.txt', 'r')); // creates file with resource as content $file = TempFile::withName('my-file.txt', new \SplFileInfo('some/file.txt')); // creates file from existing file (existing file is copied) // create for existing file $file = TempFile::new('some/file.txt'); // note: will be deleted at the end of the script // create with string content $file = TempFile::for('some contents'); // create with resource $file = TempFile::for(\fopen('some/file.txt', 'r')); // create from another file (existing file is copied) $file = TempFile::for(new \SplFileInfo('some/file.txt')); // create image $image = TempFile::image(); // temporary 10x10 image with 'jpg' as the extension $image = TempFile::image(100, 50); // customize the dimensions $image = TempFile::image(type: 'gif'); // customize the image type $image = TempFile::image(name: 'my-image.png'); // customize the file name
使用 TempFile
实例
/** @var \Zenstruck\TempFile $file */ $file->contents(); // string - the file's contents $file->refresh(); // self - clearstatcache() on the file (refreshes metadata) $file->delete(); // self - delete the file // is instance of \SplFileInfo $file->getMTime(); // int - last modified timestamp $file->getExtension(); // string - file extension
长时间运行进程
通过跟踪创建的文件并在脚本结束时使用 register_shutdown_function
清理,自动删除创建的 TempFile
。如果使用长时间运行的PHP进程(如工作进程或Swoole/RoadRunner运行时),文件将不会在进程停止前被清理。这会导致内存泄漏,因为跟踪的创建文件在内存中增长。为了解决这个问题,您需要将您的进程中的某个事件挂钩,该事件允许您清除此类泄漏并手动调用 TempFile::purge()
。
Symfony 集成
提供了一个简单的服务,用于在每个请求结束时和在使用 symfony/messenger 后处理作业后清理 TempFile
。
使用方法:注册该服务
# config/packages/zenstruck_temp_file.yaml services: Zenstruck\TempFile\Bridge\Symfony\PurgeTempFiles: autoconfigure: true