CakePHP 3:带缓存的 find()

CakePHP 3: find() with cache

关于get()方法,我看了here:

Like find() get has caching integrated. You can use the cache option when calling get() to perform read-through caching

但是后来,在专门介绍find()方法的部分(here)中,没有提到缓存,没有缓存的例子,cache选项是支持的选项中未提及。

所以我想知道:find()方法可以使用cache选项吗?如果可以,怎么做?

谢谢。


感谢 ndm。所以:

$query = $this->Pages->find('all');
$query->cache('all_pages');

$this->set('pages', $query->all());

或者(更简单):

$query = $this->Pages->find('all')->cache('all_pages');

$this->set('pages', $query->all());

查询构建器不支持通过选项进行缓存,它有一个单独的方法可供使用,Query::cache(),您可以像

一样使用它
$query = $table->find();
$query->cache('cache_key');

$query->cache('cache_key', 'configName');

$query->cache(function($query) {
    return md5(
        serialize($query->clause('select')) .
        serialize($query->clause('where'))
    );
});

// ...

get() 通过选项支持缓存,因为这是配置内部查找调用的唯一方法,因为它会立即执行,因此 get() 可以 return 抛出可能的错误和 return一个实体。

我已经研究了 cakephp 3 文档和其他资源,以了解在查询中使用 cache() 的很好示例,但没有找到任何内容(文档只给出了简短的片段,而不是完整的示例)

我的模型中的方法存在非常相似的问题 /src/Model/Table/MetaTagTable。php

namespace App\Model\Table;

use Cake\ORM\Table;

class MetaTagTable extends Table
{
    /**
     * Get meta tags from db table
     * 
     * @return array
     */
    function getMetaTags($controller, $action, $hasSearchParamFlag)
    {
        $hasSearchParamFlag = (int) $hasSearchParamFlag;

        return $this
            ->find()
            ->select(['tag', 'type'])
            ->where(
                [
                    'controller'=> $controller,
                    'action'=> $action,
                    'have_search_param'=> $hasSearchParamFlag,
                ]
            )
            ->all()
            ->cache(
                function () use ($controller, $action, $hasSearchParamFlag) 
                {
                    return "getMetaTags-$controller, $action, $hasSearchParamFlag";
                },
                'middle'
            );
    }
}

上面的例子显示了一个致命错误:

Error: Call to undefined method Cake\ORM\ResultSet::cache()  

official cakephp 3 doc doesn't give a full example, about how cache() with query builder works, so using @ndm 答案并尝试了几种不同的代码变体我使我的代码工作,只是在 ->all() 方法调用之前移动 cache() 调用:

function getMetaTags($controller, $action, $hasSearchParamFlag)
{
    $hasSearchParamFlag = (int) $hasSearchParamFlag;

    return $this
        ->find()
        ->select(['tag', 'type'])
        ->where(
            [
                'controller'=> $controller,
                'action'=> $action,
                'have_search_param'=> $hasSearchParamFlag,
            ]
        )                              
        ->cache(
            function () use ($controller, $action, $hasSearchParamFlag) 
            {
                return "getMetaTags-$controller, $action, $hasSearchParamFlag";
            },
            'middle'
        )                        
        ->all()
        ->toArray();
}

因为cache()方法属于trait"QueryTrait",Cake\ORM\Queryclass需要调用cache()方法,Cake\ORM\ResultSet不需要。

现在一切正常,尽情享受吧!