ExSite::Cache is a generic cache tool for saving re-useable data.
The cache is an in-memory hash of arbitrary data values. The data can be indexed based on an arbitrary amount of indexing data, so that the cache can store completely unrelated data with low risk of collision.
The primary use in ExSite is to remember results of database queries, so that we don't need to make a DB server call to re-fetch something we've already fetched (but forgotten).
For instance, if you've fetched data record #123 from table XYZ, you could save it in cache this way:
my $cache = new ExSite::Cache;
$cache->save($data,"XYZ","123");
The first value is the data to save; the remaining values (there can be any number) are used to uniquely index the data. In this case, the table name and record number are sufficient to uniquely specify this piece of data.
If later someone asks for the same data, eg:
$db->fetch("XYZ",123);
then you could first check the cache for a value before querying the the database:
$data = $cache->get("XYZ",123);
if (! $data) { # go to database...
If practice, all of the above is done automatically by the ExSite::DB class.
This version of the Cache tool uses ExSite::Store for the underlying data management. This approach allows our cache to be persistent across multiple requests.
You can provide any number of key values to index the data in the cache. These are hashed together to give the aggregate hash key which is used to look up the data in future.
The first of the key values provided is the primary key, which has a special use. All cache items that share a primary key are remembered, and those cache items can be cleared at a stroke, using:
$cache->clear("XYZ");
Example: The purpose of this is to allow you to cache the results of numerous queries, eg:
select * from page where page_id=99
select * from page where section_id=4 & type="template"
These 2 queries would result in at least 2 separate entries in the cache. If the primary key for both of these cache entries was ``page'', then the keys for these cache entries would be saved in the key index under ``page''. At some later time, if we updated some records in the page table, we might not know if any of the data in the cache has now been superceded. The safe thing to do is expire all page entries in the cache:
$cache->clear("page");
If you perform more complex queries involving joins of multiple tables, eg.
select content_id,name from page,content where page.type="template" & content.page_id=page.page_id
Then you can index these under a compound primary key, by using an array reference for your primary key, eg.
$cache->save($data,["page","content"],...);
Then a request to clear either ``page'' OR ``content'' would clear that cache entry.
You can also remove a single cache entry as follows:
# remove it using original indexing data
$cache->delete("XYZ",123);
# remove it using MD5 hash cache key
$cache->clear_key($key);
The wipe the whole cache clean, use:
$cache->clear_all;