【问题标题】:how to use cache in cakePHP3如何在 cakePHP3 中使用缓存
【发布时间】:2018-03-15 16:06:11
【问题描述】:

我正在尝试使用 cakePHP3 中的缓存来存储查询结果。

我声明了一个名为“bl”的缓存适配器

配置/app.php:

/**
 * Configure the cache adapters.
 */
'Cache' => [
    'default' => [
        'className' => 'File',
        'path' => CACHE,
        'url' => env('CACHE_DEFAULT_URL', null),
    ],

    'bl' => [
        'className' => 'File',
        'path' => CACHE . 'bl/',
        'url' => env('CACHE_DEFAULT_URL', null),
        'duration' => '+1 week',

    ],

src/Controller/UsersController.php:

use Cake\Cache\Cache;
...
        public function test()
        {
                $this->autoRender = false;
                $this->loadModel('Users');
                $Users = $this->Users->find('all');
                $Users->cache('test', 'bl');
                debug(Cache::read('test', 'bl'));
        }

调试返回“false”。

tmp/cache/bl/ 目录创建良好,但没有生成缓存文件。

我错过了什么吗?

【问题讨论】:

  • 我试过这段代码public function test() { $this->autoRender = false; $users = $this->Users->find('all')->toArray(); $users->cache('test_cache', 'bl'); //Cache::write('test_cache', $users, 'bl'); debug(Cache::read('test_cache', 'bl')); } 缓存看起来在等待一个不是数组的对象:Error: Call to a member function cache() on array File /opt/myapp/src/Controller/UsersController.php Line: 43

标签: caching cakephp cakephp-3.0 query-builder


【解决方案1】:

您的查询永远不会被执行,因此它永远不会被缓存。通过调用 all()toArray() 或迭代它等来运行查询...

另见

【讨论】:

    【解决方案2】:

    您没有调用正确的方法,您需要使用 Cache::write() 而不是 Users->cache()。我在下面更新了您的代码:

    use Cake\Cache\Cache;
    ...
            public function test()
            {
                    $this->autoRender = false;
                    $this->loadModel('Users');
                    $Users = $this->Users->find('all');
                    Cache::write('cache_key_name', $Users, 'bl');
                    debug(Cache::read('cache_key_name', 'bl'));
            }
    

    https://book.cakephp.org/3.0/en/core-libraries/caching.html#writing-to-a-cache

    【讨论】:

    • 我试过你的代码,但我收到了这个错误:Error: You cannot serialize or unserialize PDO instances If you are using SQL keywords as table column names, you can enable identifier quoting for your database connection in config/app.php. If you want to customize this error message, create src/Template/Error/pdo_error.ctp
    • 我的回答是正确的并且回答了你的缓存问题。请参阅 ndm 对您的其他问题的回复。
    【解决方案3】:

    我能够通过您的 2 个答案找到解决方案,最终代码是:

    public function test()
    {
        $this->autoRender = false;
        $users = $this->Users->find('all')->toArray();
        Cache::write('test_cache', $users, 'bl');
        debug(Cache::read('test_cache', 'bl'));
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-01-18
      • 2012-12-25
      • 1970-01-01
      • 1970-01-01
      • 2015-03-14
      相关资源
      最近更新 更多