alyakin / dictionary-cache-service
Dictionary caching service for Redis-compatible stores (Redis, KeyDB, Valkey, etc.).
Requires
- php: ^7.4
- illuminate/redis: ^8.0
Requires (Dev)
- mockery/mockery: ^1.5
- phpunit/phpunit: ^9.0 || ^10.0
This package is auto-updated.
Last update: 2025-04-07 21:33:39 UTC
README
Dictionary caching based on Redis-compatible stores (Redis, KeyDB, Valkey, Dragonfly, Ardb, etc.).
📌 Contents
- 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
Installation
Install via Composer:
composer require alyakin/dictionary-cache-service
Methods
__construct
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 );
setContext
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');
setDataProvider
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(); } );
setTTL
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);
getTTL
Retrieves the TTL of the cache key. If not set, returns default (3600).
preload
Loads data into the cache using the data provider if it is not initialized.
hasItem
Checks if a specific item exists in the cache.
Parameters:
itemId
(required, string) → Item to check.
$inCart = $userCartCache->hasItem($productId); return $inCart;
hasItems
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;
getAllItems
Retrieves all cached items.
exists
Checks if the cache exists for the scope.
addItems
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.
removeItem
Removes a specific item from the cache.
Parameters:
item
(required, string) → Item to remove.
$this->cartCache->removeItem((string) $event->productId);
keepAlive
Refreshes the expiration time of the cache key without modifying TTL.
$this->cartCache->removeItem((string) $event->productId)->keepAlive();
clear
Clears the cached data but keeps TTL settings.
Supported Databases
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
Requirements
The package requires:
- PHP 7.4+
- Laravel 8+
- Redis-compatible storage
Want to Contribute?
Check out the open issues — especially those labeled good first issue!
Feel free to fork the repo, open a PR, or suggest improvements.
License
This package is open-source and available under the MIT License.