h4kuna/ dir
轻松创建目录
v0.1.7
2024-07-15 05:34 UTC
Requires
- php: >=8.0
- nette/utils: ^2.2 || ^3.0 || ^4.0
Requires (Dev)
- nette/tester: ^2.4
- phpstan/phpstan-strict-rules: ^1.4
README
一个抽象类提供路径和准备文件系统。
通过composer安装
composer require h4kuna/dir
如何使用
您的路径由您的类表示。在这个仓库中准备了类TempDir。以相同的方式创建自己的类。
这些目录存在
- 临时目录
/documet/root/temp
- 日志目录
/documet/root/log
- 存储目录
/documet/root/data
示例
创建StorageDir。
class StorageDir extends \h4kuna\Dir\Dir { }
开始使用。
$storageDir = new StorageDir('/documet/root/data'); // dir in constructor does not check $storageDir->create(); // if dir from constructor does not exist, let's check and create $subDir = $storageDir->dir('foo/bar'); $filepath = $subDir->filename('lucky', 'jpg'); $filepath2 = $storageDir->filename('baz/foo/happy.jpg'); echo $filepath; // /documet/root/data/foo/bar/lucky.jpg echo $filepath2; // /documet/root/data/baz/foo/happy.jpg
在文件系统中存在路径 /documet/root/data/foo/bar
和 /documet/root/data/baz/foo
。
您的存储目录由类StorageDir表示,您可以通过依赖注入来使用它。
class MyClass { public function __construct(private StorageDir $storageDir) { } }
检查目录
如果目录不存在,则方法create
抛出IOException。如果目录存在,但不可写,则方法checkWriteable
抛出继承自IOException
的DirIsNotWriteableException
。
use h4kuna\Dir; try { $fileInfo = (new Dir\Dir('/any/path')) ->create() ->checkWriteable() ->fileInfo('foo.txt'); } catch (Dir\Exceptions\IOException $e) { // dir is not writable } var_dump($fileInfo->getPathname()); // /any/path/foo.txt
错误使用
在构造函数中只使用不带最后一个正斜杠的绝对路径,如下例所示。
这是错误的
new StorageDir('/documet/root/data/')
new StorageDir('documet/root/data/')
new StorageDir('documet/root/data')
正确的是只有new StorageDir('/documet/root/data')
。
在方法dir()
和filename()
中,不要在路径的开始和结束使用斜杠。
这是错误的
$storageDir->dir('/foo/')
$storageDir->dir('/foo')
$storageDir->dir('foo/')
正确的是只有$storageDir->dir('foo')
或子目录$storageDir->dir('foo/bar')
。