Caching
A cache is a store where you put data to enhance application performance by reducing frequent computations or database queries.
For example, if your store displays product categories with counts, querying the database every time is slow. Instead, cache the result and reuse it for future requests.
Lightpack provides a simple, flexible cache library with multiple drivers and a clean API.
Quick Start
Lightpack comes pre-configured with a default file-based cache service. Just use:
cache()->set();
cache()->get();
cache()->has();
cache()->delete();
cache()->flush();
cache()->forever();
cache()->remember();
cache()->rememberForever();
NOTE: Set appropriate write permissions on the storage directory for file cache.
set()
Store an item in the cache.
Parameters: key, value, seconds (expiry in seconds, not minutes).
cache()->set('name', 'Bob', 300); // 5 minutes
- Pass
0as seconds for a “forever” cache (5 years).
get()
Retrieve an item from cache by key. Returns null if not found or expired.
$name = cache()->get('name'); // Bob or null
has()
Check if a key exists in the cache.
if (cache()->has('name')) { ... }
delete()
Remove an item from the cache.
cache()->delete('name');
flush()
Clear all items from the cache store.
cache()->flush();
forever()
Store an item “forever” (actually 5 years).
cache()->forever('site_theme', 'Marble');
remember()
Retrieve an item if present, otherwise compute, store, and return it.
$value = cache()->remember('expensive', 300, function() {
return computeExpensiveThing();
});
rememberForever()
Like remember(), but stores the value “forever”.
$value = cache()->rememberForever('expensive', function() {
return computeExpensiveThing();
});
Available Drivers
Lightpack provides several cache drivers:
- FileDriver: Stores cache in files (default).
- ArrayDriver: Stores cache in memory (non-persistent, useful for testing).
- NullDriver: Disables cache (all operations are no-ops).
- DatabaseDriver: Stores cache in a database table (requires schema).
- RedisDriver: Stores cache in Redis (supports key prefixing).
You can switch the cahce driver by altering CACHE_DRIVER key in .env file
Database Migration
If using database as cache driver, you need to migrate schema for storing cache entries.
Create schema migration file:
php console create:migration --support=cache
Run migration:
php console migrate:up