A simple caching engine which is highly customizable. This library can be used to implement caching at 3 areas, application, server and database. The cached items are Time-Based, meaning that each item will have a Time-to-Live. Once passed, item will be considered as expired.
If you are using composer to manage your dependencies, then it is possible to install the library by including the entry "webfiori/cache":"*"
in the require
section of your composer.json
file to install the latest release.
Another way to include the library is by going to releases and download the latest release and extract compressed file content and add them to your include directory.
Build Status |
---|
The normal workflow of using the library is as follows:
- Cache items are created.
- Cache items are accessed from cache as needed.
- Cached items are re-validated with every access.
- If expired, items are removed from the cache or re-created.
Creating cache entries is performed using the method Cache::set($key, $data)
. The method accepts two mandatory parameters, first one is the key of cache item and second argument is the data that will be cached. Data can be of any type.
Cache::set('my_item', 'Any Data');
This would create a cache entry with duration of 60 seconds. This means if a user tries to access same item after 60 seconds, cache will miss.
To customize time-to-live, a third parameter can be passed which represents the time at which the item will be kept in cache.
Cache::set('my_item', 'Any Data', 3600); //Keep the item for one hour in the cache.
To override and revalidate specific cache item, a fourth boolean argument can be used to achieve that.
Cache::set('my_item', 'Any Data', 3600, true);
There are two approaches to get cache items, one is retrieve only and the second one is retrieve or create.
This approach will attempt to search for the item in cache and return it if found. If not found, null is returned.
$data = Cache::get('my_item');
This approach is recommended as it will initially attempt to retrieve the item from the cache. If not found, it will create it using a custom callback.
$data = Cache::get('my_item', function () {
return 'This is a test.';
}, 3600);
The callback accepts passing parameters as an array as shown in the next sample.
$data = Cache::get('my_item', function ($p1, $p2) {
return 'This is a test. '.$p1.' '.$p2;
//Output: 'This is a test. Hello World'
}, 3600, ['Hello', 'World']);
Cache::has('item_key');
Cache::delete('item_key');
Cache::flush();
Enabling cache.
Cache::setEnabled(true);
Disabling cache.
Cache::setEnabled(false);
Developer can create his own custom cache store. To achieve this, the interface webfiori\cache\Store
must be implemented.
$driver = new MyCustomDriver();
Cache::setDriver($driver);
This library is licensed under MIT license.