【问题标题】:How can I create a session-backed Laravel Cache store?如何创建会话支持的 Laravel 缓存存储?
【发布时间】:2015-07-25 22:02:20
【问题描述】:

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

我希望使用 Laravel Cache 门面来做到这一点,但使用某种语法表明我希望在用户会话中保留一份副本除了普通 Redis 缓存。

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

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

【问题讨论】:

    标签: laravel caching laravel-5 laravel-5.1


    【解决方案1】:

    与 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 并且没有机会对其进行测试 :) 如果您有任何问题,请告诉我,我会非常高兴让它工作:)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-12-16
      • 1970-01-01
      • 1970-01-01
      • 2021-07-28
      • 2019-05-02
      • 1970-01-01
      相关资源
      最近更新 更多