Вопрос

Basically, I am implementing own cache system. Ideally, it'll look like this:

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

But that is a holy grail that I do not hope to find. Basically, the $CACHE->start() checks if cache is a hit or a miss, and whether it is a hit, it skips the //CODE until $CACHE->end().

The best I have come so far, is:

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

Since PHP supports anonymous functions, I was thinking of:

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

But this code has a problem that code is not in the same variable scope. Any chance to bypass that?

Update: I have since switched to ruby, which allows to pass the block to a function, being perfect for this task.

Это было полезно?

Решение

Zend Framework includes a cache that skips $cache->end() by assuming the remainder of the page is part of the cached content.

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

// ....

// No need for end

It doesn't fit all use-cases though.

(A modified version of my comment)

Другие советы

How about a default approach? The example below is quite common and is used it 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;
    }

It is basic key value storage, and doesn't require any closure tricks.

In the anonymous function you can use the 'use' keyword to bring variables into that scope.

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

You might implement the first one with goto, but it's a very rude approach, and you will be looked at as an enemy of programming.

I'd go for the second one if I had to choose.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top