PHP缓存结构(如果是HIT则跳过代码块)

时间:2011-11-07 14:34:03

标签: php caching scope control-structure

基本上,我正在实现自己的缓存系统。理想情况下,它看起来像这样:

$CACHE->start($name);
   //CODE
$CACHE->end();

但这是我不希望发现的圣杯。基本上,$ CACHE-> start()检查缓存是命中还是未命中,以及它是否是命中,它跳过// CODE,直到$ CACHE-> end()。

我到目前为止最好的是:

if ($CACHE->start($name)) {
   //CODE
}
$CACHE->end();

由于PHP支持匿名函数,我想:

$CACHE->make($name, function() {
   //CODE
});

但是这段代码存在代码不在同一变量范围内的问题。有机会绕过那个吗?

更新:我已经切换到ruby,它允许将块传递给函数,非常适合此任务。

3 个答案:

答案 0 :(得分:2)

默认方法怎么样?下面的示例非常常见,并使用memcached f.e。

   function doSomething()
   {
       $oCache = SomeRegistry::get('Cache');

       // Check for cached results.
       if ($oCache->exists('someKey')) {
           return $oCache->get('someKey');
       }
       $sCached = getSomeThing();
       $this->set('someKey', $sCached);
       return $sCached;
    }

这是基本的键值存储,不需要任何关闭技巧。

答案 1 :(得分:1)

在匿名函数中,您可以使用'use'关键字将变量带入该范围。

<?php
function () use ($container, $anythingElseYouMayWantToUse) {
    //...
}

您可以使用goto实现第一个,但这是一种非常粗鲁的方法,您将被视为编程的敌人。

如果必须选择,我会选择第二个。

答案 2 :(得分:1)

Zend Framework包含一个cache,它通过假设页面的其余部分是缓存内容的一部分来跳过$cache->end()

// Default cache ID is calculated from $_SERVER['REQUEST_URI']
$zendPageCache->start();

// ....

// No need for end

它不适合所有用例。

(我的评论的修改版本)