Hi,
I don't really like this idea of variables : it add more code either in the view or the controller, and it doesn't feel nice.
On the other hand, I like this idea of cache... Event if you think it's too complex / overkill.
Why not find some way in the middle ? Not use some cache like file/APC/memcache, but just keep the data in memory for the execution of the script ?
you can use a static variable for that ; either in your class, or directly in the method (depending on "does it make sense to share that cache between methods of the class ?")
To illustrate this idea, here's a quick portion of code ; consider this class :
class A {
public function test($param) {
static $cache = array();
if (isset($cache[$param])) {
var_dump("cache hit : $param = {$cache[$param]}");
return $cache[$param];
} else {
// Fetch from DB (here, simulated ^^ )
$cache[$param] = mt_rand(0, 9999);
var_dump("cache miss : $param = $cache[$param]");
return $cache[$param];
}
}
}
The test method uses a static variable (there will be one, and only one instance of that variable, shared by any instances of the class) to store the data that has been fetched from the DB.
If you call this that way :
$a = new A();
$b = new A();
$a->test(10); // miss
$a->test(15); // miss
$b->test(10); // hit
$b->test(25); // miss
$a->test(25); // hit
You'll get this :
string 'cache miss : 10 = 3745' (length=22)
string 'cache miss : 15 = 7800' (length=22)
string 'cache hit : 10 = 3745' (length=21)
string 'cache miss : 25 = 8623' (length=22)
string 'cache hit : 25 = 8623' (length=21)
Each time the method is called with a new parameter, it's a miss, and you go to the DB. But when it's called when a parameter already used once, the data is in memory -- and you don't go to the DB ;-)
Wouldn't that help ? I'm guessing, in your case, the A class is the view helper, btw ;-) ANd the mt_rand would be a DB query ^^
As a sidenote : this should not be done for too big objects, as it will use some RAM... and don't have lots of those...
Edit : as you are using Zend Framework, you might be interested in using Zend_Memory instead of that static variable : it deal with stuff like the amount of RAM taken (it can delete data from the "cache" if needed, for instance), if I remember correctly.
Also : yes, you are still calling the method many times... But it's better than doing the query... and, this way, neither the View nor the Controller has to care about any kind of "cache" : it's not their job.
And also : I've be using this technic for years without any problem (as long as I only store small objects this way, and not too many of them) ; And I'm not the only one using this ; Drupal uses this too, for instance.