如何创建会话支持的Laravel缓存存储?

如何创建会话支持的Laravel缓存存储?,laravel,caching,laravel-5,laravel-5.1,Laravel,Caching,Laravel 5,Laravel 5.1,出于性能原因,我希望在PHP会话中存储一些数据,而不是在Redis缓存中 我希望使用Laravel Cache facade来实现这一点,但使用某种语法表示,除了正常的Redis缓存之外,我还希望在用户会话中保留一个副本 然后在检索时,我希望缓存存储首先在会话中查找,然后只有在未找到时才向Redis发出网络请求 我不是在寻找完整的代码,但希望能有一些指导。与Laravel捆绑的缓存驱动程序都不提供这种双层存储,因此您需要自己实现一个新的驱动程序。幸运的是 不会太复杂的 首先,创建新的驱动程序:

出于性能原因,我希望在PHP会话中存储一些数据,而不是在Redis缓存中

我希望使用Laravel Cache facade来实现这一点,但使用某种语法表示,除了正常的Redis缓存之外,我还希望在用户会话中保留一个副本

然后在检索时,我希望缓存存储首先在会话中查找,然后只有在未找到时才向Redis发出网络请求


我不是在寻找完整的代码,但希望能有一些指导。

与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));
  });
}
'session_redis' => [
  'driver' => 'redis',
  'connection' => 'default',
],
config/cache.php中提供配置:

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));
  });
}
'session_redis' => [
  'driver' => 'redis',
  'connection' => 'default',
],
并在config/cache.php.env文件中将缓存驱动程序设置为该驱动程序:

'default' => env('CACHE_DRIVER', 'session_redis'),
请记住,我只更新了get()put()方法。您可能需要覆盖更多的方法,但这样做应该与get/put一样简单

要记住的另一件事是,我通过查看Laravel代码生成了上述代码片段,但没有机会对其进行测试:)如果您有任何问题,请告诉我,我将非常乐意让它工作:)