我已经调查了 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 没有提供完整的示例,说明 cache() 与查询构建器的工作原理,因此使用@ndm 答案并尝试几种不同的代码变体,我使我的代码工作,只是移动 cache() 调用在 ->all() 方法调用之前:
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\Query 类调用 cache() 方法,而不是为 Cake\ORM\ResultSet。
现在一切正常,尽情享受吧!