1. INTRODUCTION
Caching saves a result so you can reuse it on later requests. For example, you can save a list of articles for ten minutes instead of reading it from the database on every page visit.
Kristal Framework stores cached values in storage/cache/. Add this import near the top of your PHP file:
use Backend\Core\Cache;
Your code chooses what to save and when to read it.
2. SAVING VALUES
Use add() with a name, value and duration:
Cache::add("site_notice", "New tutorials are available!", "30 minutes");
Cache::add("navigation_items", [
"Home",
"Articles",
"Contact",
], "1 day");
The name identifies the saved value. Saving under the same name replaces both its value and expiry time. The method returns true when the file is saved.
Durations can be written as 10 minutes, 2 hours or 1 day. To keep a value until you remove it, use never or leave out the duration:
Cache::add("site_label", "My Website", "never");
Use clear names with letters, numbers and underscores. Strings, numbers, booleans and arrays make straightforward cache values.
3. READING VALUES
Read a value using the name you saved it under:
$notice = Cache::get("site_notice");
if ($notice !== null)
{
echo esc_html($notice);
}
get() returns null when an entry is missing or has expired. Expired entries are removed when read.
Note!
Check for null as shown above. A saved false, zero or empty array can still be a useful result.
4. CACHING A DATABASE RESULT
This example uses the Articles class from Database. Add the imports near the top of your file, then run the remaining code where you need the article list:
use Backend\Core\Cache;
use Backend\Database\Articles;
$published = Cache::get("published_articles");
if ($published === null)
{
$articles = new Articles();
$published = (array) $articles->table()
->where("published", 1)
->orderBy("id", "desc")
->get();
Cache::add("published_articles", $published, "10 minutes");
}
The first request reads the database and saves the result. Later requests use that saved list until ten minutes have passed. The next request then loads a fresh list.
If results differ by language, include the language in the cache name, such as articles_en and articles_fi.
5. REMOVING CACHED DATA
After editing an article, remove the old list so the next request reads the updated data:
Cache::remove("published_articles");
To clear all cached entries:
Cache::clear();
Important!
clear() removes all cache entries, including those used by other pages. Use remove() when only one saved result has changed.
6. STORAGE AND TROUBLESHOOTING
Let the Cache class manage the files in storage/cache/. Keep this folder protected and only allow trusted code to write there.
If a value isn’t saved, check the folder’s write permissions. If it disappears too soon, check the duration and debug log. An invalid duration makes the entry expire immediately.
Entries saved with never remain until removed. Cache reads and writes work in production mode too.
