I just found myself a bit in a bind on what to do. I have a list, generated from the database that is returned by a method. Now this method is called multiple times from two different places (out of scope) so I either have to globalize the result somehow, like make it an attribute in a higher up class or pass it around. Both are very unappealing and rather ugly to maintain.
Instead, I opted for a mini cache in the originating class. The setup is quiet simple, so I now also use this in base classes that get implemented down the line.
private $_localCache = NULL;
public function myFunc()
{
if (!isset($this->_localCache[__METHOD__]))
{
$value = time(); // Create value here
$this->_localCache[__METHOD__] = $value;
return $value;
}
else
{
return $this->_localCache[__METHOD__];
}
}
The code is as simple as it looks. First you create a private attribute _localCache which is used for caching. Each cache is identified by a key in the _localCache array. That way you can reuse this multiple times very fast and easy. As key, I use the method name. This is especially hand because you don’t have to change any code if you refactor the method or the class.
As with usual caching, it checks if a cache is set, then returns that, otherwise, grabs the real data and caches it. This works of course without any additional cache tools installed, so even though memcached and xcache are wonderful for caching things like this often, they might not be available or simply not really usable.
A prime example is when you know that the value does not change in the execution of this script, but might change between reloads. This way you know for certain you will always use the same data inside the script, while also being sure the next reload fetches the data new.
For static things that get read more often than written to between loads, are better of in a real cache system. If the data changes even less than that, say every few months or so and it’s not a lot, you could also optimize by just hard coding it as an array or class.
0 Responses
Stay in touch with the conversation, subscribe to the RSS feed for comments on this post.
You must be logged in to post a comment.