デストラクタ内でfile_put_contents()
を呼び出すと、ファイルがSERVER_ROOT
...(Yikes!)に書き込まれます。PHPファイルの作成/デストラクタ内での書き込み
tldr:
私はおそらく、シリアル化されたクラスのインスタンスを含む配列を、キャッシュしたいです。私は、今のところ、unserialize()/file_get_contents()
とserialize()/file_put_contents()
を使ってキャッシュを実装するクラスを作成し、より汎用的なCacheクラスの背後にその機能を隠していると考えました。
<?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"));
?>
(私のクライアントのホストは、など、メモリやPEARを共有しているかどうかはわからない)デストラクタでflush()
への呼び出しを参照してください?実装固有の機能なので、私は本当にpublic flush()
機能を望んでいません。
質問に答えることはできませんが、なぜWebサーバーユーザーが 'SERVER_ROOT'を書き込み可能にするのですか? –
'$ this-> filename'には何がありますか? – hakre
私はOPのコードを変更して動作上の問題を表示しました... $ this-> filename is "cache" –