Cache
You’ll often want to cache the results of expensive or long running operations to save CPU time and respond to future requests faster. Alchemy provides a Cache
type for easily interacting with common caching backends.
Configuration
Cache conforms to Service
and can be configured like other Alchemy services with the config
function. Out of the box, providers are provided for Redis and SQL based caches as well as an in memory mock cache.
If you’re using the Cache.sql()
cache configuration, you’ll need to add the Cache.AddCacheMigration
migration to your database’s migrations.
Interacting with the Cache
Storing Items in the Cache
You can store values to the cache using the set()
function.
The third parameter is optional and if not passed the value will be stored indefinitely.
Storing Custom Types
You can store any type that conforms to CacheAllowed
in a cache. Out of the box, Bool
, String
, Int
, and Double
are supported, but you can easily store your own types as well.
Retreiving Cache Items
Once set, a value can be retrived using get()
.
Checking for item existence
You can check if a cache contains a specific item using has()
.
Incrementing and Decrementing items
When working with numerical cache values, you can use increment()
and decrement()
.
Removing Items from the Cache
You can use delete()
to clear an item from the cache.
Using remove()
, you can clear and return a cache item.
If you’d like to clear all data from a cache, you may use wipe.
Adding a Custom Cache Provider
If you’d like to add a custom provider for cache, you can implement the CacheProvider
protocol.
Then, add a static configuration function for using your new cache backend.