Dictionary caching based on Redis-compatible stores (Redis, KeyDB, Valkey, Dragonfly, Ardb, etc.).
- Installation
- Methods
- Creating an object
- Setup scope for cache
- Set data provider
- Set cache Time To Live (TTL)
- Get cache Time To Live (TTL)
- Mannualy preload cache
- Check one item in cache
- What items from the list are in the cache
- Get all elements from cache
- Checking is cache loaded
- Mannualy add element in to cache
- Mannualy remove element from the cache
- Reset TTL countdoun
- Clear Cache for the scope
- Supported Databases
- Requirements
- Contributing
- License
Install via Composer:
composer require alyakin/dictionary-cache-service
Initializes the service with optional context, data provider, and Redis connection.
Parameters:
contextId
(optional, string) β Unique identifier for the cache.dataProvider
(optional, Closure) β Function that returns an array of items to be cached.redisInstance
(optional, RedisConnection) β Custom Redis connection instance.
$userCartCache = new \App\Services\DictionaryCacheService(
contextId: $userId,
dataProvider: $myDataProviderCallback
);
Sets the cache key using a context ID and an optional prefix. All class methods use the scope set by this method.
Parameters:
contextId
(required, string) β Unique identifier for the context.key
(optional, string) β Prefix for the cache key (default:"dictionary"
).
$userCartCache->setContext('user_'.$userId, 'cart');
$userFavoriteProductsCache->setContext('user_'.$userId, 'favorite_products');
Sets a function that provides data for cache preloading. This method will only be called if the cache has not been initialized yet.
Parameters:
dataProvider
(required, Closure) β Function returning an array of items.
$userCartCache->setDataProvider(
function () use ($userId) {
return UserCart::whereUserId($userId)->pluck('id')->toArray();
}
);
Sets the TTL (time-to-live) for the cache key.
Parameters:
ttl
(required, int) β TTL in seconds (must be >= 1).
$userCartCache = new \App\Services\DictionaryCacheService();
$userCartCache
->setContext('user_'.$userId, 'cart')
->setDataProvider(fn() => ['19', '33', '7'])
->setTTL(3600*24);
Retrieves the TTL of the cache key. If not set, returns default (3600).
Loads data into the cache using the data provider if it is not initialized.
Checks if a specific item exists in the cache.
Parameters:
itemId
(required, string) β Item to check.
$inCart = $userCartCache->hasItem($productId);
return $inCart;
Checks which items from the list exist in the cache.
Parameters:
itemIds
(required, array) β List of item IDs.
$productList = Product::recomendedFor($productID)->get()->pluck('id')->toArray();
$productsInCart = $userCartCache->hasItems($productList);
$recomendations = array_diff($productList, $productsInCart);
return $recomendations;
Retrieves all cached items.
Checks if the cache exists for the scope.
Adds multiple items to the cache.
public function handle(ProductAddedToCart $event): void {
$this->cartCache->setContext("user_{$event->userId}", 'cart');
if ($this->cartCache->exists()) {
$this->cartCache->addItems([$event->productId]);
}
}
Parameters:
items
(required, array) β Items to add.
Removes a specific item from the cache.
Parameters:
item
(required, string) β Item to remove.
$this->cartCache->removeItem((string) $event->productId);
Refreshes the expiration time of the cache key without modifying TTL.
$this->cartCache->removeItem((string) $event->productId)->keepAlive();
Clears the cached data but keeps TTL settings.
The service works with Redis-compatible databases supported by Laravel's Redis driver:
- Redis (all versions)
- KeyDB
- Valkey
- Dragonfly (tested with Redis-compatible API)
- Ardb
The package requires:
- PHP 7.4+
- Laravel 8+
- Redis-compatible storage
Check out the open issues β especially those labeled good first issue!
Feel free to fork the repo, open a PR, or suggest improvements.
This package is open-source and available under the MIT License.