Reputation: 3415
For performance reasons, I'd like to store some data in the PHP session rather than my Redis cache.
I'm hoping to use the Laravel Cache facade to do this, but with some sort of syntax to indicate that I'd like a copy to be kept in the user's session in addition to the normal Redis cache.
Then on retrieval, I want the Cache store to look first in the Session, then only if not found do the network request to Redis.
I'm not looking for full code, but some direction would be appreciated.
Upvotes: 2
Views: 1252
Reputation: 40899
None of cache drivers bundled with Laravel offers this kind of double layer storage, so you'll need to implement a new driver yourself. Luckily, it won't be too complicated.
First, create your new driver:
class SessionRedisStore extends RedisStore {
public function get($key) {
return Session::has($key) ? Session::get($key) : parent::get($key);
}
public function put($key, $value, $minutes, $storeInSession = false) {
if ($storeInSession) Session::set($key, $value);
return parent::put($key, $value, $minutes);
}
}
Next, register the new driver in your AppServiceProvider:
public function register()
{
$this->app['cache']->extend('session_redis', function(array $config)
{
$redis = $this->app['redis'];
$connection = array_get($config, 'connection', 'default') ?: 'default';
return Cache::repository(new RedisStore($redis, $this->getPrefix($config), $connection));
});
}
provide config in your config/cache.php:
'session_redis' => [
'driver' => 'redis',
'connection' => 'default',
],
and set your cache driver to that driver in config/cache.php or .env file:
'default' => env('CACHE_DRIVER', 'session_redis'),
Please keep in mind that I've updated only get() and put() methods. You might need to override some more methods, but doing that should be just as simple as for get/put.
Another thing to keep in mind is that I've produced above snippets by looking at the Laravel code and didn't have a chance to test it :) Let me know if you have any issues and I'll be more than happy to get it working :)
Upvotes: 4