此包已被废弃且不再维护。未建议替换包。

此包适用于需要创建临时目录的项目。

dev-main 2023-10-14 22:33 UTC

This package is auto-updated.

Last update: 2024-07-15 00:27:06 UTC


README

Software License PHP Composer

此包允许您快速在系统临时目录中创建、使用和删除临时目录。

以下是一个创建临时目录并删除它的快速示例

use Hellomohsinhello\TempDir\TempDir;

$tempDir = (new TempDir())->create();

// Get a path inside the temporary directory
$tempDir->path('temporaryfile.txt');

// Delete the temporary directory and all the files inside it
$tempDir->delete();

安装

您可以通过composer安装此包

composer require hellomohsinhello/temp-dir

使用

创建临时目录

要创建临时目录,只需在TemporaryDirectory对象上调用create方法。

(new TempDir())->create();

或者,使用TempDir对象上的静态make方法。

TempDir::make();

默认情况下,临时目录将创建在系统临时目录中带有时间戳的目录中(通常是/tmp)。

命名您的临时目录

如果您想为临时目录使用自定义名称而不是时间戳,请在create方法之前使用字符串参数$name调用name方法。

(new TempDir())
   ->name($name)
   ->create();

默认情况下,如果存在具有给定参数的目录,则将抛出异常。您可以通过结合调用name方法和force方法来覆盖此行为。

(new TempDir())
   ->name($name)
   ->force()
   ->create();

为临时目录设置自定义位置

您可以通过将字符串参数$location传递给TemporaryDirectory构造函数来设置一个自定义位置,以便在其中创建临时目录。

(new TempDir($location))
   ->create();

make方法也接受一个$location参数。

TempDir::make($location);

最后,您可以使用$location参数调用location方法。

(new TempDir())
   ->location($location)
   ->create();

确定临时目录内的路径

您可以使用path方法确定临时目录中文件或目录的完整路径。

$temporaryDirectory = (new TempDir())->create();
$temporaryDirectory->path('dumps/datadump.dat'); // return  /tmp/1485941876276/dumps/datadump.dat

清空临时目录

使用empty方法删除临时目录内的所有文件。

$temporaryDirectory->empty();

删除临时目录

一旦您处理完临时数据,您可以使用delete方法删除整个临时目录。其中的所有文件都将被删除。

$temporaryDirectory->delete();

当对象销毁时删除临时目录

如果您希望在对象实例在其定义的作用域内没有更多引用时自动删除文件系统目录,您可以在TemporaryDirectory对象上启用deleteWhenDestroyed()。

function handleTemporaryFiles()
{
    $temporaryDirectory = (new TempDir())
        ->deleteWhenDestroyed()
        ->create();

    // ... use the temporary directory

    return; // no need to manually call $temporaryDirectory->delete()!
}

handleTemporaryFiles();

您还可以在对象实例上调用unset()。

测试

composer test

致谢

许可证

MIT许可证(MIT)。请参阅许可证文件获取更多信息。