caching - How to pass a callback function with parameters for ob_start in PHP? -
i've been following this tutorial on caching function. run problem of passing callback function cache_page()
ob_start
. how can pass cache_page()
along 2 paramters $mid
, $path
ob_start
, along lines of
ob_start("cache_page($mid,$path)");
of course above won't work. here's example code:
$mid = $_get['mid']; $path = "cachefile"; define('cache_time', 12); function cache_file($p,$m) { return "directory/{$p}/{$m}.html"; } function cache_display($p,$m) { $file = cache_file($p,$m); // check cache file exists , not old if(!file_exists($file)) return; if(filemtime($file) < time() - cache_time * 3600) return; header('content-encoding: gzip'); // if so, display cache file , stop processing echo gzuncompress(file_get_contents($file)); exit; } // write cache file function cache_page($content,$p,$m) { if(false !== ($f = @fopen(cache_file($p,$m), 'w'))) { fwrite($f, gzcompress($content)); fclose($f); } return $content; } cache_display($path,$mid); ob_start("cache_page"); ///// here's problem
the signature of callback ob_start
has be:
string handler ( string $buffer [, int $phase ] )
your cache_page
method has incompatible signature:
cache_page($content, $p, $m)
this means expecting different arguments ($p
, $m
) ob_start
pass callback. there no way make ob_start
change behavior. not send $p
, $m
.
in linked tutorial, cache file name derived request, e.g.
function cache_file() { return cache_path . md5($_server['request_uri']); }
from code take want define file path manually. can this:
$p = 'cache'; $m = 'foo'; ob_start(function($buffer) use ($p, $m) { return cache_page($buffer, $p, $m); });
this passes compatible callback ob_start
call cache_page
function output buffer , closes on $p
, $m
callback.
Comments
Post a Comment