One abstract class provide path and prepare filesystem.
composer require h4kuna/dir
Your path is represented by your class. In this repository is prepared class TempDir. By same way create own class.
These dirs are exist:
- temp dir
/documet/root/temp - log dir
/documet/root/log - storage dir
/documet/root/data
Create StorageDir.
class StorageDir extends \h4kuna\Dir\Dir
{
}Start to use.
$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.jpgOn file system exists path /documet/root/data/foo/bar and /documet/root/data/baz/foo.
Your storage dir is represented by class StorageDir and you can use it by dependency injection.
class MyClass {
public function __construct(private StorageDir $storageDir) {
}
}If directory does not exist, the method create throw IOException. If directory exists, but is not writeable, the method checkWriteable throw DirIsNotWriteableException extends from IOException.
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.txtIn constructor use only absolute path without last slash like in example.
This is incorrect
new StorageDir('/documet/root/data/')new StorageDir('documet/root/data/')new StorageDir('documet/root/data')
Correct is only new StorageDir('/documet/root/data').
In methods dir() and filename() don't use slashes on the begin and end path.
This is incorrect
$storageDir->dir('/foo/')$storageDir->dir('/foo')$storageDir->dir('foo/')
Correct is only $storageDir->dir('foo') or sub dir $storageDir->dir('foo/bar').