如何在PHP中传递带有ob_start参数的回调函数?

时间:2015-04-25 06:32:57

标签: php caching ob-start

我一直关注缓存功能this tutorial。我遇到了为cache_page()传递回调函数ob_start的问题。如何将cache_page()以及两个参数$mid$path传递给ob_start,这与

相似
  ob_start("cache_page($mid,$path)");

当然以上都行不通。这是示例代码:

$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 that cache file exists and is not too old
    if(!file_exists($file)) return;

    if(filemtime($file) < time() - CACHE_TIME * 3600) return;

    header('Content-Encoding: gzip');

    // if so, display cache file and stop processing
    echo gzuncompress(file_get_contents($file));

    exit;
}

  // write to 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 the problem

1 个答案:

答案 0 :(得分:5)

signature of the callback to ob_start has to be

from django import forms

Class EmailForm(forms.Form):
    email = forms.EmailField(required=True, max_length=1000)

您的string handler ( string $buffer [, int $phase ] ) 方法具有不兼容的签名:

cache_page

这意味着您期望不同的参数(cache_page($content, $p, $m) $p)而不是$m将传递给回调。无法使ob_start更改此行为。它不会发送ob_start$p

在链接教程中,缓存文件名是从请求派生的,例如

$m

从您的代码我想要手动定义文件路径。你可以做的是:

function cache_file()
{
    return CACHE_PATH . md5($_SERVER['REQUEST_URI']);
}

这会将兼容的回调传递给$p = 'cache'; $m = 'foo'; ob_start(function($buffer) use ($p, $m) { return cache_page($buffer, $p, $m); }); ,它会将带有输出缓冲区的ob_start函数和closes over $p and $m调用到回调中。