在析构函数中调用file_put_contents()
时,会导致文件写入SERVER_ROOT
...(Yikes!)变通办法?在析构函数中创建/写入PHP文件
tldr:
我想缓存阵列,可能包含序列化类的实例。我现在认为,我会写一个类,它使用unserialize()/file_get_contents()
和serialize()/file_put_contents()
来实现缓存,然后将其功能隐藏在更通用的缓存类中。 (我不知道如果我的客户端的主机将有共享内存或梨等)
<?php
class CacheFile {
private $filename;
private $data;
private $dirty = false;
function __construct($filename) {
$this->filename = $filename;
$this->load();
}
function __destruct() {
// Calling file_put_contents within a destructor causes files to be written in SERVER_ROOT...
$this->flush();
}
private function load() {
if(!file_exists($this->filename)) {
$this->data = array();
}
else {
$this->data = unserialize(file_get_contents($this->filename));
// todo
}
$this->dirty = false;
}
private function persist() {
file_put_contents($this->filename, serialize($this->data));
$this->dirty = false;
}
public function get($key) {
if(array_key_exists($key, $this->data)) {
return $this->data[$key];
}
else {
return false;
}
}
public function set($key, $value) {
if(!array_key_exists($key, $this->data)) {
$dirty = true;
}
else if($this->data[$key] !== $value) {
$dirty = true;
}
if($dirty) {
$this->dirty = true;
$this->data[$key] = $value;
}
}
public function flush() {
if($this->dirty) {
$this->persist();
}
}
}
$cache = new CacheFile("cache");
var_dump($cache->get("item"));
$cache->set("item", 42);
//$cache->flush();
var_dump($cache->get("item"));
?>
看到析构函数调用flush()
?我真的不想拥有public flush()
函数,因为它是特定于实现的。
不是您的问题的答案,但为什么SERVER_ROOT可由Web服务器用户写入? –
'$ this-> filename'是什么? – hakre
我更改了OP中的代码以显示问题的实际操作...... $ this-> filename是“cache” –