【问题标题】:Caching page by parts; how to pass variables calculated in cached parts into never-cached parts?按部分缓存页面;如何将缓存部分中计算的变量传递到从不缓存的部分?
【发布时间】:2010-04-02 05:36:42
【问题描述】:

假设我有这样的代码......

if (!$data = $cache->load("part1_cache_id")) {
  $item_id = $model->getItemId();
  ob_start();
  echo 'Here is the cached item id: '.$item_id;
  $data = ob_get_contents();
  ob_end_clean();
  $cache->save($data, "part1_cache_id");
}
echo $data;

echo never_cache_function($item_id);

if (!$data_2 = $cache->load("part2_cache_id")) {
  ob_start();
  echo 'Here is the another cached part of the page...';
  $data_2 = ob_get_contents();
  ob_end_clean();
  $cache->save("part2_cache_id");
}
echo $data_2;

据你所见,我需要将 $item_id 变量传递给 never_cache_function,但如果第一个部分被缓存(part1_cache_id),那么我无法获取 $item_id 值。我看到了唯一的解决方案 - 序列化来自第一部分的所有数据(包括 $item_id 值);然后缓存序列化的字符串并在每次执行脚本时对其进行反序列化...

这样的……

if (!$data = $cache->load("part1_cache_id")) {
  $item_id = $model->getItemId();
  $data['item_id'] = $item_id;
  ob_start();
  echo 'Here is the cached item id: '.$item_id;
  $data['html'] = ob_get_contents();
  ob_end_clean();
  $cache->save( serialize($data), "part1_cache_id" );      
}
$data = unserialize($data);
echo $data['html']

echo never_cache_function($data['item_id']);

还有其他方法可以做到这一点吗? 我正在寻找最高性能的解决方案。

谢谢

更新 另一个问题是 - 如何在不将页面分成两个模板的情况下将这种缓存实现到控制器中?有可能吗?

PS:请不要推荐 Smarty,我对实现自定义缓存真的很感兴趣。

【问题讨论】:

    标签: php caching


    【解决方案1】:

    您需要更改缓存函数以返回对象或数组。它总是有一个data 字段,其中包含数据和您需要的任何其他字段,即item_id

    Array(
      data => '<h1>whatever data you were caching before</h1>'
      item_id => 32,
      cache_date => '2010-03-01 12:32:01'
    )
    

    这将很好地序列化/反序列化,您将可以访问附加到缓存数据的其他参数。

    这有意义吗?

    【讨论】:

    • 感谢您的评论。据我了解,这与我所说的相似。唯一的区别是序列化和反序列化例程包含在缓存前端中。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-03
    • 2019-03-08
    • 1970-01-01
    • 1970-01-01
    • 2012-02-11
    • 1970-01-01
    相关资源
    最近更新 更多