我正在嘗試在不使用內存或臨時文件的情況下創建「虛擬」文件。當使用require
或include
時,「虛擬」文件需要通過file_exists()
進行檢查,同時不會發出任何錯誤或警告。如何創建虛假/「虛擬」文件?
允許你實現自己的協議處理程序,並與all the other filesystem functions(如
fopen()
,fread()
等)流使用。
...其中file_exists()
就是其中之一。 The docs page指出:
從PHP 5.0.0開始,這個函數也可以和一些URL包裝一起使用。請參閱Supported Protocols and Wrappers以確定哪些包裝器支持
stat()
功能族。
我嘗試有建立一個自定義,虛擬文件包
class VirtualFileWrapper
{
public $context;
public function stream_open($path, $mode, $options, &$opened_path)
{
return TRUE;
}
public function stream_stat()
{
var_dump(__METHOD__);
$data = [
'dev' => 0,
'ino' => getmyinode(),
'mode' => 'r',
'nlink' => 0,
'uid' => getmyuid(),
'gid' => getmygid(),
'rdev' => 0,
'size' => 0,
'atime' => time(),
'mtime' => getlastmod(),
'ctime' => FALSE,
'blksize' => 0,
'blocks' => 0,
];
return array_merge(array_values($data), $data);
}
}
stream_wrapper_register('virtual', 'VirtualFileWrapper');
$file = fopen("virtual://foo", 'r+');
// Executes VirtualFileWrapper::stream_stat()
fstat($file);
// Executes no VirtualFileWrapper method
file_exists($file);
雖然fstat()
函數執行的方法,file_exists()
不執行任何流類方法。
我怎麼能得到一個虛擬的流封裝到(與file_exists()
)工作?
我充分認識到tempnam(__DIR__, '')
將通過兩種:
var_dump(tempnam(__DIR__, ''));
返回true
require tempnam(__DIR__, '');
沒有錯誤
,但我不想使用臨時文件,因爲可能是更好的方式(性能明智)。
你不能。 file_exists()需要一個字符串作爲其參數。你可以傳入一個實現魔術__toString()方法的對象,但是file_exists會將這個字符串作爲'stat()'並失敗,因爲這個文件並不存在。 –
@MarcB其實[** Drupal **有這個工作](http://drupal.stackexchange.com/a/24233/55237)。我只是無法弄清楚vfsStream是如何在源代碼中混淆的。 – kaiser
你爲什麼試圖完成這個?我認爲創建一個假文件是一個非常奇怪的做法。 – Jehy