0

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.

Rok Kralj
  • 46,826
  • 10
  • 71
  • 80
  • One more idea is with GOTO statement, but that is so ugly I do not plan to use. – Rok Kralj Nov 07 '11 at 14:38
  • You can access particular variables by adding `use ($var1, $var2, …)` to the anonymous function definition, but there's no way to make all variables from the parent scope available. – Michael Mior Nov 07 '11 at 14:39
  • 1
    if ($cache->start()) { .... } $cache->end(); may be about as good as it gets. Zend Framework includes a cache that skips $cache->end() by assuming the remainder of the page is part of the cached content. Doesn't fit all cases though. – rrehbein Nov 07 '11 at 14:42
  • Everyone got +1 :) I am still looking for SIMPLE ideas. – Rok Kralj Nov 07 '11 at 16:00
  • @rrehbein: Please write your comment as answer, so I can accept it. It helped the most, so I want to accept your answer. – Rok Kralj Nov 12 '11 at 22:29

3 Answers3

2

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.

Wesley van Opdorp
  • 14,888
  • 4
  • 41
  • 59
1

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.

sallaigy
  • 1,524
  • 1
  • 13
  • 12
1

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)

rrehbein
  • 4,120
  • 1
  • 17
  • 23