我需要设置一些HTTP报头"Expires", "Cache-Control","Last-Modified",用于CSS文件、Images文件、js文件、等(网页内容)。
我读到有一些功能,通过
Configure::write('Asset.timestamp', true); // In core.php
和Helper类的assetTimestamp方法。
现在的问题是:它是如何使用的?
我阅读了HtmlHelper代码,在css方法中,第361行有这个:
$url = $this->assetTimestamp($this->webroot($path));
已解决。
首先你必须考虑通过Apache。你可以看看这个指南:http://httpd.apache.org/docs/2.2/caching.html
问题是CakePHP有一个方法来做这个。而且非常好。
我将为CSS文件解释这一点。当然也可以用于JS内容。
1)在core.php文件中(app/config/下)取消注释:
Configure::write('Asset.filter.css', 'css.php');
这一行告诉CakePHP通过"CSS .php"脚本将所有请求路由到CSS文件。顾名思义,它是一个过滤器。在那里我们可以做任何我们想做的事。
2)创建"css.php"文件。你必须在app/webroot/
下创建它在那里,你可以获取浏览器请求的文件,并应用一些缓存HTTP头。
类似:
$filepath = CSS . $regs[1]; //There are some variables that are can be used in this script, take a look to de docs.
$output = file_get_contents($filepath);
header("Date: " . date("D, j M Y G:i:s ", $templateModified) . 'GMT');
header("Content-Type: text/css");
header("Expires: " . gmdate("D, d M Y H:i:s", time() + DAY) . " GMT"); //WEEK or MONTH are valid as well
header("Cache-Control: max-age=86400, must-revalidate"); // HTTP/1.1
header("Pragma: cache"); // HTTP/1.0
print $output;
就是这样!在那里,你的内容将以指定的标题提供,浏览器将知道可以缓存它们。
看一下:
http://www.bunchacode.com/programming/get-cakephp-build-in-css-compression-to-work/有一个很好的版本的css.php也缩小了它