0

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

$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​​,它允许将块传递给一个函数,非常适合这个任务。

4

3 回答 3

2

默认方法怎么样?下面的例子很常见,使用它 memcached fe

   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;
    }

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

于 2011-11-07T14:39:57.090 回答
1

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

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

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

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

于 2011-11-07T14:41:31.007 回答
1

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

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

// ....

// No need for end

但它并不适合所有用例。

(我评论的修改版)

于 2011-11-14T21:10:12.303 回答