Bra*_*aby 5 php serialization caching destructor
在file_put_contents()析构函数中调用时,它会导致文件写入SERVER_ROOT...(Yikes!)解决方法?
tldr:
我想缓存一个数组,可能包含序列化的类实例.我想,现在,我会编写一个使用unserialize()/file_get_contents()和实现缓存的类,serialize()/file_put_contents()然后在更通用的Cache类后面隐藏它的功能.(我不知道我的客户主机是否有共享内存或PEAR等)
<?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") );
?>
Run Code Online (Sandbox Code Playgroud)
查看flush()析构函数中的调用?我真的不想拥有这个public flush()功能,因为它是特定于实现的.
我假设你没有指定一个完整的合格路径$this->filename.
在某些PHP配置中,当调用析构函数时(在脚本关闭阶段),工作目录可以更改.然后相对路径解析到另一个位置.
与PHP手册中的相关说明进行比较:
注意:
在脚本关闭期间调用的析构函数已经发送了HTTP头.脚本关闭阶段的工作目录可能与某些SAPI(例如Apache)不同.
如果您将该路径设为绝对路径,它将按预期工作.
编辑:当您更新代码时,这是确保您获得绝对路径的简单方法:
$cache = new CacheFile(realpath("cache"));
Run Code Online (Sandbox Code Playgroud)
或者在构造函数中更好:
$this->filename = realpath($filename);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1277 次 |
| 最近记录: |