CakePHP 3:具有缓存的find()

CakePHP 3:具有缓存的find()

问题描述:

关于 get()方法,我读了此处


像find()一样已经集成了缓存。您可以在调用get()来执行只读缓存时使用cache选项。

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

但是稍后,在 find()方法(此处),未提及缓存,没有有关缓存和 cache 选项的示例

But later, in the section dedicated to the find() method (here), the cache is not mentioned, there are no examples for the cache and the cache option is not mentioned among the supported options.

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

So I would like to know: can I use the cache option with the find() method? If so, how?

谢谢。

感谢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(),您将使用类似的方法

The query builder doesn't suport caching via options, it has a separate method that is to be used, Query::cache(), which you'd use like

$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'))
    );
});

// ...

请参见

  • Cookbook > Query Builder > Caching Loaded Results
  • \Cake\Datasource\QueryTrait::cache()

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

get() supports caching via an option as that's the only way to configure the internal find call, since it's being executed immediately so that get() can return throw possible errors and return an entity.