【问题标题】:How to cache static content (css, images,js files) in CakePHP2?如何在 CakePHP2 中缓存静态内容(css、图像、js 文件)?
【发布时间】:2011-10-04 15:25:40
【问题描述】:

我需要设置一些 HTTP 标头“Expires”、“Cache-Control”、 “Last-Modified”,用于 CSS 文件、图像文件、js 文件等资源, 等(Webroot 内容)。

我读到有一些功能,通过

   Configure::write('Asset.timestamp', true); // In core.php

还有 Helper 类的assetTimestamp 方法。

现在的问题是:它是如何使用的?

我阅读了 HtmlHelper 代码,在 css 方法中,第 361 行是这样的:

$url = $this->assetTimestamp($this->webroot($path));

【问题讨论】:

  • 面包师在谷歌上搜索“为以下资源指定至少一周后的到期时间”

标签: php http cakephp caching cakephp-2.0


【解决方案1】:

解决了。

首先你必须考虑通过 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 版本也可以缩小它。

【讨论】:

  • 我们可以用这个来做js和css。我们如何向图像添加过期标头?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-05-06
  • 1970-01-01
  • 2015-04-08
  • 2014-04-03
  • 1970-01-01
  • 1970-01-01
  • 2012-09-19
相关资源
最近更新 更多