vfsStream的用例如下:
$directories = explode('/', 'path/to/some/dir');
$structure = [];
$reference =& $structure;
foreach ($directories as $directory) {
$reference[$directory] = [];
$reference =& $reference[$directory];
}
vfsStream::setup();
$root = vfsStream::create($structure);
$file = vfsStream::newFile('file')
->at($root) //should changes be introduced here?
->setContent($content = 'Some content here');
vfsStream::inspect(new vfsStreamStructureVisitor())->getStructure()
的输出是
Array
(
[root] => Array
(
[path] => Array
(
[to] => Array
(
[some] => Array
(
[dir] => Array
(
)
)
)
)
[file] => Some content here
)
)
是否可以将文件插入特定目录,例如dir
目录下?
答案 0 :(得分:1)
是的,显然可以使用addChild()
方法将儿童添加到vfsStreamFirectory
:
但是,我在API Docs中找不到允许轻松遍历结构以添加内容的简单方法。对于这个特殊情况,这是一个可怕的hacky ,如果每个路径元素有多个文件夹,则会失败。
基本上我们必须逐步遍历每个级别,验证名称是否是我们要添加文件的名称,然后在找到它时添加。
use org\bovigo\vfs\vfsStream;
use org\bovigo\vfs\vfsStreamDirectory;
use org\bovigo\vfs\visitor\vfsStreamStructureVisitor;
$directories = explode('/', 'path/to/some/dir');
$structure = [];
$reference =& $structure;
foreach ($directories as $directory) {
$reference[$directory] = [];
$reference =& $reference[$directory];
}
vfsStream::setup();
$root = vfsStream::create($structure);
$file = vfsStream::newFile('file')
->setContent($content = 'Some content here');
$elem = $root;
while ($elem instanceof vfsStreamDirectory)
{
if ($elem->getName() === 'dir')
{
$elem->addChild($file);
}
$children = $elem = $elem->getChildren();
if (!isset($children[0]))
{
break;
}
$elem = $children[0];
}
print_r(vfsStream::inspect(new vfsStreamStructureVisitor())->getStructure());
答案 1 :(得分:0)