与 Laravel 捆绑的缓存驱动程序都没有提供这种双层存储,因此您需要自己实现一个新的驱动程序。幸运的是,
不会太复杂。
首先,创建您的新驱动程序:
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);
}
}
接下来,在您的 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));
});
}
在您的 config/cache.php 中提供配置:
'session_redis' => [
'driver' => 'redis',
'connection' => 'default',
],
并在 config/cache.php 或 .env 文件中将您的缓存驱动程序设置为该驱动程序:
'default' => env('CACHE_DRIVER', 'session_redis'),
请记住,我只更新了 get() 和 put() 方法。您可能需要覆盖更多方法,但这样做应该与 get/put 一样简单。
要记住的另一件事是,我通过查看 Laravel 代码生成了上面的 sn-ps 并且没有机会对其进行测试 :) 如果您有任何问题,请告诉我,我会非常高兴让它工作:)