CachedIni class

唐突ですが、parse_ini_file 関数 の結果を 簡単にキャッシュしたいならこんな感じのコードはどうでしょう。

< ?php
// License: The MIT License
class CachedIni {
    var $cache_dir;
    var $filename;
    var $cache_filename;
    var $section;

    function CachedIni($cache_dir, $filename, $section = false)
    {
        $this->cache_dir = $cache_dir;
        $this->filename = $filename;
        $this->cache_filename = $cache_dir . DIRECTORY_SEPARATOR . md5($filename);
        $this->section = $section;
    }

    function getData()
    {
        return $this->isCached() ? $this->load() : $this->store();
    }

    function isCached()
    {
        clearstatcache();
        return file_exists($this->cache_filename) && (filemtime($this->filename) < = filemtime($this->cache_filename));
    }

    function load()
    {
        return unserialize(file_get_contents($this->cache_filename));
    }

    function store()
    {
        $data = parse_ini_file($this->filename, $this->section);
        $f = fopen($this->cache_filename, 'wb');
        fwrite($f, serialize($data));
        fclose($f);
        return $data;
    }
}
?>

使うときは以下のように。

// 使用前
$config = parse_ini_file($file, true);

// 使用後
$ini = new CachedIni('path/to/cache_dir', $file, true);
$config = $ini->getData();

ファイルのロックはしてませんので、各自追加してください。

PHP 5.1.2 でしか動作確認していないのですが、多分 PHP 4.3.0 以降なら動 くような気がします(file_get_contents を使っているので 4.3.0 未満は無 理)。serialize と parse_ini_file とどっちが速いのかは微妙なところです が、load() と store() をいじれば YAML でもいけるんじゃないでしょうか。