ProcessWire interface to Redis memory cache
Purpose
This module provides a simple interface to the phpredis library for caching contents in-memory. The functionality leans on ProcessWire's WireCache core library.
Compatibility
Compatible with ProcessWire 3.x
Status
Alpha, WiP, use with care
Prerequisites
The phpredis extension must be installed.
Usage
Setup
After installation, you need to enable the module in the module settings by ticking the "Active" checkbox. The server and port are preset to 127.0.0.1 and 6379.
The configuration options support connecting via unix domain sockets and using TLS. You can optionally enable authentication.
Basics
CacheRedis registers itself as a PW API variable with the name "redis", so you can access in all the usual ways:
$var = $redis->get('mykey');
$var = wire('redis')->get('otherkey');
$var = $this->redis->get('thirdkey'); // only within Wire derived classes
Methods
$redis->fetch($name, $expire, $func)
Retrieve a value from the cache by the given name. If $func is given and no cached entry was found, call $func and use its return value instead, saving that in the cache with the given expiry time.
Alternatively, you can pass an array of names to the method. In that case, an associative array of names and values is returned, with only those keys present that were found in the cache. If you do that, you must not pass a $func parameter.
$redis->store($name, $expire, $value)
Save the value in the cache with the given name as the key and the specified expire time. If $expire is not set, CacheRedis::expireDaily is assumed (24h).
$redis->delete($name)
Deletes the entry with the given key name from the cache.
$redis->flush()
Delete all entries from the cache.
$redis->renderFile($filename, $expire, array $options)
This method behaves similar to $files->render()
and actually delegates the file rendering to that method (when creating the cache). The important difference is that this method caches the output according to the given expiry value, rather than re-rendering the file on every call.
If there are any changes to the source file $filename
the cache will be automatically re-created, regardless of what is specified for the $expire
argument.
// render primary nav from site/templates/partials/primary-nav.php
// and cache for 3600 seconds (1 hour)
echo $redis->renderFile('partials/primary-nav.php', 3600);
Parameters for renderFile:
Return
string|bool Rendered template file or boolean false on fatal error (and throwExceptions disabled)
License
Licensed under Mozilla Public License v2. See file LICENSE in the repository for details.
Credits
Ryan Cramer, creator of ProcessWire. Quite a bit of his well thought out code was taken more or less literally from his WireCache class to keep things compatible and keep from reinventing the wheel.