CakePHP中文手册【翻译】-view(视图)缓存

View(视图)缓存

1

它是什么 ?

0.10.9.2378_final以来,Cake已经支持view缓存(也称为全页缓存(Full Page Caching).不,我们没有撒谎。你现在可以缓存你的布局和view。通过缓存机制,你也可以将你的部分view标记为忽略。当你正确使用它时,此特性可以明显加快应用程序。

当你请求一个URL时,Cake首先看看请求的URL是否已经得到缓存。如果是,Cake跳过调度者(Dispatcher),并返回已经render的缓存起来的页面。如果页面不在缓存中,Cake按常规操作。

如果你已经启用了Cake的缓存特性,Cake会为将来的用户在缓存中存储正常操作的输出。当下一次请求此页面时,Cake从缓冲中取出这个页面。非常棒是不是?让我们深入下去,看看它是如何工作的。

2

它如何工作 ?

激活缓存

缺省的,view缓存机制不可用。为了激活它,首先你需要改变/app/config/core.php中的CACHE_CHECK值,将false改为true:

/app/config/core.php (部分)

define ('CACHE_CHECK', true);

本行告诉Cake你想启用view缓存。

在你想缓存的view所对应的controller里,你必须将Cache helper加到helper数组中::

var $helpers = array('Cache');

接下来,你需要指定你想缓存什么.

$cacheAction Controller变量

在本节,我们将向你展示如何告诉Cake你想缓存什么。我们可以通过设置一个Controller变量$cacheAction来完成。可以将一个$cacheAction变量设置一个数组,此数组包含你想缓存的动作,以及你想将此数据保存多久的时间(以秒为单位).此时间值也可以为一个strtotime()的友好字符串(例如,'1 day'或’60 seconds').

假使我们有一个ProductsController,而且它有一些我们打算缓存的东西。下面的例子向你说明如何使用$cacheAction变量告诉Cake缓存某些特定的Controller动作。

$cacheAction 实例

//Cache a few of the most oft visited product pages for six hours:

var $cacheAction = array(

    'view/23/'  => 21600,

    'view/48/'  => 21600

);

 

//Cache an entire action. In this case the recalled product list, for one day:

var $cacheAction = array('recalled/' => 86400);

 

//If we wanted to, we could cache every action by setting it to a string:

//that is strtotime() friendly to indicate the caching time.

var $cacheAction = "1 hour";

 

//You can also define caching in the actions using $this->cacheAction = array()...

view构造内容

有这样一个情况,你可能不想缓存一个已经缓存的view的某部分。如果你有某些强调新产品或类似东西的元素,你可能想告诉Cake缓存view,但是除了这一小部分。

你可以告诉Cake不要缓存view<cake:nocache></cake:nocache>标签所包含的内容,让缓存引擎跳过这部分内容。

<cake:nocache> 实例

<h1> New Products! </h1>

<cake:nocache>

<ul>

<?php foreach($newProducts as $product): ?>

<li>$product['name']</li>

<?endforeach;?>

</ul>

</cake:nocache>

清除缓存

首先,你需要注意,如果数据库做出改变,Cake会自动清除缓存。例如,如果你的一个view使用了来自Post model里的信息,而且那里有一个对Post做出的INSERTUPDATE,或DELETE操作,Cake会清除view的缓存。

但是也许有一种情况你不想清除某些你自己指定的缓存文件。为了实现此,Cake提供了一个clearCache函数,此函数全局可用的:

<cake:nocache> 实例

//Remove all cached pages that have the controller name.

clearCache('controller');

 

//Remove all cached pages that have the controller_action name.

clearCache('controller_action/');

 

//Remove all cached pages that have the controller_action_params name.

//Note: you can have multiple params

clearCache('controller_action_params');

 

//You can also use an array to clear muliple caches at once.

clearCache(array('controller_action_params','controller2_action_params));

3

需记住的某些事

关于view的缓存,下面是一些你需要记住的事情:

1.    /app/config/core.php 里,将CACHE_CHECK设置为true来启用缓存

2.    在你想缓存viewcontroller里,你必须将Cache helper加到helper的数组里。

3.    为了缓存某些特定的URL,使用Controller里的$cacheAction

4.    为了阻止缓存已经缓存的view的某些特定部分,使用<cake:nocache> </cake:nocache>

5.    当数据库做出改变时,Cake自动清除指定的缓存备份。

为了手动删除部分缓存,使用clearCache().
Last Updated:2006年12月5日
posted @ 2006-11-30 09:54  张太国  阅读(3620)  评论(0编辑  收藏  举报