Last updated January 10, 2013. Created by mitchell on January 10, 2013.
Log in to edit this page.
The new cache API introduces a new way to “remove” a cache item. In addition to the existing delete methods where cache entries are permanently deleted, cache entries can now also be invalidated.
- Delete methods
- delete(), deleteMultiple(), deleteTags(), deleteAll(), deleteExpired()
- Invalidate methods
- invalidate(), invalidateMultiple(), invalidateTags(), invalidateAll()
Invalidation is like a “soft delete” where items are not deleted but only marked as invalid, meaning “not fresh” or “not fresh enough”. An item automatically becomes invalid when the expire time specified in the set() call is reached, or it may explicitly be marked as invalid using the functions listed above. The invalid items are not returned by a normal get() call, so in most ways they act as they have been deleted. However, by passing TRUE as the second argument for get(), it is possible to fetch the invalid value.
<?php
// Explicit invalidation
cache()->set('foo', 123);
cache()->get('foo'); // Returns a cache item
cache()->invalidate('foo');
cache()->get('foo'); // Returns FALSE
cache()->get('foo', TRUE); // Returns a cache item
cache()->garbageCollection();
cache()->get('bar', TRUE); // Returns FALSE
// Expired items
cache()->set('bar', 123, REQUEST_TIME + 60);
cache()->get('bar'); // Returns a cache item
// The next lines run 61 seconds later in a new request.
cache()->get('bar'); // Returns FALSE
cache()->get('bar', TRUE); // Returns a cache item
cache()->garbageCollection();
cache()->get('bar', TRUE); // Returns FALSE
?>The examples are based on the database cache backend. Some cache backends may have different garbage collection strategies that yield different results for the calls to get with TRUE as the second parameter.
Cache items should be deleted if they are no longer considered useful. This is relevant e.g. if the cache item contains references to data that has been deleted. On the other hand, it may be relevant to just invalidate the item if the cached data may be useful to some callers until the cache item has been updated with fresh data. The fact that it was fresh a short while ago may often be sufficient.
Invalidation is particularly useful to protect against stampedes. Rather than having multiple concurrent requests updating the same cache item when it expires or is deleted, there can be one request updating the cache, while the other requests can proceed using the stale value. As soon as the cache item has been updated, all future requests will use the updated value.