Caching API Reference
About 1274 wordsAbout 4 min
Overview
Complete API reference for the Filterable caching system.
HasFilterableCache Trait
All methods available on any class using the HasFilterableCache trait.
cache()
Enable caching with optional TTL.
public function cache(DateTimeInterface|int|null $ttl = null): selfParameters:
$ttl- Time to live in seconds or DateTimeInterface instance
Returns: Self for method chaining
Example:
Post::filter()->cache(3600)->get();
Post::filter()->cache(now()->addHour())->get();remember()
Alias for cache() method.
public function remember(DateTimeInterface|int|null $ttl = null): selfExample:
Post::filter()->remember(1800)->get();cacheForever()
Cache results permanently until manually flushed.
public function cacheForever(): selfReturns: Self for method chaining
Example:
Category::filter()->cacheForever()->get();cacheTags()
Set cache tags for organization and bulk invalidation.
public function cacheTags(array $tags): selfParameters:
$tags- Array of tag strings
Returns: Self for method chaining
Example:
Post::filter()
->cache(3600)
->cacheTags(['posts', 'content'])
->get();Warning
Cache tags require Redis or Memcached. Not supported by file/database drivers.
scopeByUser()
Scope cache by authenticated user ID.
public function scopeByUser(int|string|null $userId = null): selfParameters:
$userId- User ID (defaults toauth()->id())
Returns: Self for method chaining
Example:
// Automatic user ID
Post::filter()
->cache(1800)
->scopeByUser()
->get();
// Explicit user ID
Post::filter()
->cache(1800)
->scopeByUser(123)
->get();scopeByTenant()
Scope cache by tenant ID for multi-tenant applications.
public function scopeByTenant(int|string $tenantId): selfParameters:
$tenantId- Tenant identifier
Returns: Self for method chaining
Example:
Post::filter()
->cache(3600)
->scopeByTenant(tenant()->id)
->get();scopeBy()
Add a custom cache scope.
public function scopeBy(string $key, mixed $value): selfParameters:
$key- Scope key name$value- Scope value
Returns: Self for method chaining
Example:
Post::filter()
->cache(3600)
->scopeBy('organization', $orgId)
->scopeBy('department', $deptId)
->get();withScopes()
Set multiple cache scopes at once.
public function withScopes(array $scopes): selfParameters:
$scopes- Associative array of scope key-value pairs
Returns: Self for method chaining
Example:
Post::filter()
->cache(3600)
->withScopes([
'organization' => $orgId,
'department' => $deptId,
'region' => $region,
])
->get();cacheProfile()
Use a predefined cache profile from configuration.
public function cacheProfile(string $profile): selfParameters:
$profile- Profile name from config
Returns: Self for method chaining
Example:
// Uses settings from config/filterable.php profiles
Post::filter()
->cacheProfile('heavy_reports')
->get();cacheWhen()
Cache only when a condition is true.
public function cacheWhen(bool|callable $condition, DateTimeInterface|int|null $ttl = null): selfParameters:
$condition- Boolean or callable returning boolean$ttl- Optional TTL override
Returns: Self for method chaining
Example:
// Boolean condition
Post::filter()
->cacheWhen(!auth()->user()->isAdmin(), 3600)
->get();
// Callable condition
Post::filter()
->cacheWhen(fn() => !app()->isLocal(), 1800)
->get();cacheUnless()
Cache unless a condition is true (inverse of cacheWhen).
public function cacheUnless(bool|callable $condition, DateTimeInterface|int|null $ttl = null): selfParameters:
$condition- Boolean or callable returning boolean$ttl- Optional TTL override
Returns: Self for method chaining
Example:
Post::filter()
->cacheUnless(request()->has('refresh'), 3600)
->get();flushCache()
Flush all cached results for this filterable class.
public function flushCache(): boolReturns: True if cache was flushed
Example:
$filter = new PostFilter();
$filter->flushCache(); // Flushes all PostFilter cachesflushCacheByTags()
Flush cache by specific tags.
public function flushCacheByTags(?array $tags = null): boolParameters:
$tags- Array of tags (defaults to instance tags)
Returns: True if cache was flushed
Example:
$filter = new PostFilter();
$filter->flushCacheByTags(['posts', 'content']);flushCacheByTagsStatic()
Static method to flush cache by tags.
public static function flushCacheByTagsStatic(array $tags): boolParameters:
$tags- Array of tags to flush
Returns: True if cache was flushed
Example:
Post::flushCacheByTagsStatic(['posts']);
PostFilter::flushCacheByTagsStatic(['posts', 'content']);isCachingEnabled()
Check if caching is enabled for this instance.
public function isCachingEnabled(): boolReturns: True if caching is enabled
Example:
$filter = Post::filter()->cache(3600);
if ($filter->isCachingEnabled()) {
// Caching is active
}getCacheTtl()
Get the cache TTL setting.
public function getCacheTtl(): DateTimeInterface|int|nullReturns: TTL value or null
getCacheTags()
Get the cache tags for this instance.
public function getCacheTags(): arrayReturns: Array of cache tags (includes auto-generated class tag)
Example:
$filter = Post::filter()
->cacheTags(['posts', 'content']);
$tags = $filter->getCacheTags();
// ['filterable:post_filter', 'posts', 'content']getCacheScopes()
Get the cache scopes for this instance.
public function getCacheScopes(): arrayReturns: Array of scope key-value pairs
getCacheProfile()
Get the current cache profile name.
public function getCacheProfile(): ?stringReturns: Profile name or null
FilterableCacheManager
Singleton cache manager for advanced operations.
getInstance()
Get the singleton instance.
public static function getInstance(): FilterableCacheManagerExample:
$manager = \Kettasoft\Filterable\Caching\FilterableCacheManager::getInstance();put()
Store a value in cache.
public function put(string $key, mixed $value, DateTimeInterface|int|null $ttl = null): boolParameters:
$key- Cache key$value- Value to cache$ttl- Time to live
Returns: True if successful
remember()
Get from cache or execute callback and cache result.
public function remember(string $key, DateTimeInterface|int|null $ttl, callable $callback): mixedParameters:
$key- Cache key$ttl- Time to live$callback- Callback to execute if cache miss
Returns: Cached or computed value
forever()
Cache a value permanently.
public function forever(string $key, mixed $value): boolrememberForever()
Remember forever version of remember().
public function rememberForever(string $key, callable $callback): mixedget()
Retrieve a value from cache.
public function get(string $key, $default = null): mixedParameters:
$key- Cache key$default- Default value if not found
Returns: Cached value or default
has()
Check if a key exists in cache.
public function has(string $key): boolforget()
Remove a value from cache.
public function forget(string $key): boolflushByTags()
Flush all cache entries with given tags.
public function flushByTags(array $tags): boolParameters:
$tags- Array of tags
Returns: True if successful
Warning
Requires Redis or Memcached cache driver.
withTags()
Set tags for the next operation.
public function withTags(array $tags): selfReturns: Self for method chaining
addScope()
Add a scope to the cache manager.
public function addScope(string $key, mixed $value): selfgenerateKey()
Generate a cache key with current scopes.
public function generateKey(string $baseKey): stringenable() / disable()
Enable or disable caching globally.
public function enable(): self
public function disable(): selfisEnabled()
Check if caching is globally enabled.
public function isEnabled(): boolCacheKeyGenerator
Generates deterministic cache keys.
generate()
Generate a cache key for a filterable operation.
public function generate(
string $filterClass,
array $filters = [],
array $providedData = [],
array $scopes = [],
?Builder $query = null
): stringParameters:
$filterClass- Filter class name$filters- Applied filters$providedData- Provided data$scopes- Cache scopes$query- Optional query builder
Returns: Generated cache key
simple()
Generate a simple cache key from components.
public function simple(string ...$components): stringReturns: Generated cache key
forUser()
Generate a user-scoped cache key.
public function forUser(string $filterClass, int|string $userId, array $filters = []): stringforTenant()
Generate a tenant-scoped cache key.
public function forTenant(string $filterClass, int|string $tenantId, array $filters = []): stringConfiguration Reference
// config/filterable.php
return [
'cache' => [
// Global enable/disable
'enabled' => env('FILTERABLE_CACHE_ENABLED', true),
// Cache driver (null = use default)
'driver' => env('FILTERABLE_CACHE_DRIVER', null),
// Default TTL in seconds
'default_ttl' => env('FILTERABLE_CACHE_TTL', 3600),
// Cache key prefix
'prefix' => env('FILTERABLE_CACHE_PREFIX', 'filterable'),
// Cache version (increment to bust all caches)
'version' => env('FILTERABLE_CACHE_VERSION', 'v1'),
// Cache profiles
'profiles' => [
'profile_name' => [
'ttl' => 7200,
'tags' => ['tag1', 'tag2'],
],
],
// Auto-invalidation
'auto_invalidate' => [
'enabled' => env('FILTERABLE_AUTO_INVALIDATE', false),
'models' => [
App\Models\Post::class => ['posts', 'content'],
],
],
// Cache tracking
'tracking' => [
'enabled' => env('FILTERABLE_CACHE_TRACKING', false),
'log_channel' => env('FILTERABLE_CACHE_LOG_CHANNEL', 'daily'),
],
],
];Environment Variables
# Enable/disable caching
FILTERABLE_CACHE_ENABLED=true
# Cache driver
FILTERABLE_CACHE_DRIVER=redis
# Default TTL (seconds)
FILTERABLE_CACHE_TTL=3600
# Cache key prefix
FILTERABLE_CACHE_PREFIX=filterable
# Cache version
FILTERABLE_CACHE_VERSION=v1
# Auto-invalidation
FILTERABLE_AUTO_INVALIDATE=true
# Cache tracking
FILTERABLE_CACHE_TRACKING=true
FILTERABLE_CACHE_LOG_CHANNEL=dailyNext Steps
