TYPO3 comes along with great cache. It's used in core at many places to speed up calls that need time to calculate and are used often.
This cache can be very useful in own extensions for the same reasons.
Usage of cache is very easy, and i want to show you how to do this. We will use cache_hash. You don't have to take care about the caching framework, read and save cache entries will be done by core.
Now let's look how we use the cache, here are a getter and a setter you may use in your extension. Remember that cache data is always an array, if you want to save strings, you have to put them into an array. The cache saving serializes the array, if you read, you get the serialized array, and you have to unserialize it for usage.
/**
* Gets the cache entry
*
* @param string $key cache key
* @param string $identifier unique identifier
* @return string serialized cache entry
*/
protected function getCache($key, $identifier) {
$cacheIdentifier = 'MyExtension-' . $identifier;
$cacheHash = md5($cacheIdentifier . $key);
return t3lib_pageSelect::getHash($cacheHash);
}
/**
* Stores data in cache
*
* @param string $key cache key
* @param string $identifier unique identifier
* @param array $data your data to store in cache
*/
protected function setCache($key, $identifier, $data) {
$cacheIdentifier = 'MyExtension-' . $identifier;
$cacheHash = md5($cacheIdentifier . $key);
t3lib_pageSelect::storeHash(
$cacheHash,
serialize($data),
$cacheIdentifier
);
}
That's all. Usage is very simple, let's use it in a function for getting some data:
public function getSpecialData($param1, $param2) {
$key = $param1 . $param2;
$cacheContent = $this->getCache($key, 'getSpecialData');
if (!$cacheContent) {
$result = array();
// process data and fill $result
// Now store the $result in cache and return
$this->setCache($key, 'getSpecialData', $result);
return $result;
} else {
return unserialize($cacheContent);
}
}
That's all. The reason why i compose the identifier with a hardcoded string is, that you may use this from different functions. This helps you to identify the cache entries. i prefer to compose the identifier with "extkey-functionName".
If you don't use caching framework, you'll find your entires in the DB table cache_hash, with DB cache framework the data is splitted and you find your identifiers in DB table cachingframework_cache_hash_tags.
The cache entries will be cleared with the normal "Clear Cache" commands.
Happy caching ;-)
nice article! thanks for sharing knowhow :-)