| 状态 | 草稿 |
|---|---|
| Todo | Proof read |
| 官方最后更新时间 | 2009/02/06 12:18 |
在 Kohana 中,你可以缓存任何数据以达到最大性能。
如今绝大多数的 web 页面都是动态生成的,通常是通过前端应用调用后端数据库。在存储对象或生成页面过程中生成缓存,这样在下次请求时可直接加载这些对象和页面。它可以减少访问次数与节约服务器资源与内存。
我该缓存什么? 任何需要大量动态生成的对象和内容。
当前的 Konhana 缓存库可以将缓存存储在各种各样的容器中,包括文件和数据库。这可以通过配置驱动来实现。被缓存的对象或内容可以通过一个强大的标签系统或它们对应的标示来加载。
关于 API 文档:
配置文件: application/config/cache.php,如果没有请从 system/config 复制一份(不明白的请看 Kohana 级联系统/模块关系图):
$config['default'] = array( 'driver' => 'file', 'params' => APPPATH.'cache', 'lifetime' => 1800, 'requests' => 1000 );
config['driver'] 设置驱动的缓存方式。提供 6 种不同的驱动:
$config['params'] 包含驱动程序的具体参数。 (在上面的例子 - 服务器缓存写入路径)
$config['lifetime'] 设置缓存的生命周期。当创建一个新缓存指定生命周期。设置为 0 意味着永远不自动删除。
$config['requests'] 在达到请求数量之前自动垃圾回收。设置为负数则会关闭垃圾回收功能。
假设你需要从数据库检索一些信息并建立相应表。如果要缓存这些内容,代码如下:
$this->cache= new Cache; $table = $this->cache->get('table'); if ( ! $table) { $table = build_table(); $this->cache->set('table', $table, array('mytag1', 'mytag2'), 3600); } echo $table;
主要有三个步骤:
$this->cache= new Cache;
$this→cache→set($id,$data,$tags = NULL, $lifetime = NULL) 用来设置缓存。
$id 主键(unique) id $data 如果 $data 不是字符串则会序列号储存。$tagsdefaults 可以为空,提供数组形式,它在群组缓存是很有用途。$lifetime 设置指定的生命周期。如果没有设置则会使用配置文件的。$data=array('Jean Paul Sartre', 'Albert Camus', 'Simone de Beauvoir'); $tags=array('existentialism','philosophy','french'); $this->cache->set('existentialists',$data,$tags);
$this→cache→get($id) 根据 $id 检索缓存并返回数据或 NULL。
print_r($this->cache->get('existentialists')); // 返回: // Array ( [0] => Jean Paul Sartre [1] => Albert Camus [2] => Simone de Beauvoir )
$this→cache→find($tag) 根据 $tag 搜索所有数据并返回一个字符串。
$food=array('French bread','French wine','French cheese'); $this->cache->set('food',$food,array('french')); print_r($this->cache->find('french')); // 返回: //Array ( [existentialists] => Array ( [0] => Jean Paul Sartre [1] => Albert Camus [2] => Simone de Beauvoir ) [food] => Array ( [0] => French bread [1] => French wine [2] => French cheese) )
这里有几个方法都可以删除缓存
$this→cache→delete($id) 根据 $id 删除一个缓冲并返回一个布尔型。
$this->cache->delete('food');
$this→cache→delete_tag($tag) 根据 $tag 删除所有的缓存项并返回一个布尔型。
$this->cache->delete_tag('french');
$this→cache→delete_all() 删除所有缓存项并返回一个布尔型。
$this->cache->delete_all();
如果你使用的是 SQlite 驱动来缓存查询的表结果:
CREATE TABLE caches( id varchar(127), hash char(40), tags varchar(255), expiration int, cache blob);