Caching
Introduction
Some data retrieval or processing tasks performed by your application may be CPU intensive or take several seconds to complete. When this is the case, it is common to cache the retrieved data for a time so it can be retrieved quickly on subsequent requests.
DreamFork provides an expressive, unified API for various caching backends. Currently, the framework supports the file driver, which stores serialized objects in the filesystem.
Configuration
The cache configuration file is located at config/cache.php. In this file, you may specify which cache driver you would like to be used by default throughout your application.
DreamFork also supports configuration via the .env file. Ensure you have the driver defined:
CACHE_DRIVER=file
Cache Usage
You may obtain a cache instance via the Cache facade. The facade provides convenient, static access to the underlying implementation of the DreamFork cache contracts.
Retrieving Items
The get method is used to retrieve items from the cache. If the item does not exist in the cache, null will be returned. You may also pass a second argument to the method specifying the default value you wish to be returned if the item doesn't exist:
use Framework\Support\Facades\Cache;
$value = Cache::get('key');
$value = Cache::get('key', 'default_value');
You may determine if an item exists in the cache using the has method. This method will return true if the value exists and is not null:
if (Cache::has('key')) {
// ...
}
Storing Items
You may use the put method to store items in the cache. You will also need to specify the number of seconds for which the value should be cached:
// Store value for 10 minutes (600 seconds)
Cache::put('key', 'value', 600);
Sometimes you may wish to retrieve an item from the cache, but also store a default value if the requested item doesn't exist. You may do this using the remember method:
$users = Cache::remember('users', 3600, function () {
return DB::table('users')->get();
});
In this example, if the users key does not exist in the cache, the closure will be executed, and its result will be stored in the cache for 3600 seconds.
Removing Items
You may remove items from the cache using the forget method:
Cache::forget('key');