如何在CakePHP2中缓存静态内容(css,images,js文件)? [英] How to cache static content (css, images,js files) in CakePHP2?

查看:187
本文介绍了如何在CakePHP2中缓存静态内容(css,images,js文件)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要为CSS文件,图片文件,js文件,
等资源设置一些HTTP头Expires,Cache-Control,
Last-Modified )。

I need to set some HTTP headers "Expires", "Cache-Control", "Last-Modified", for resources as CSS files, Images files, js files, etc (Webroot content).

我已经读过,有一些功能,通过

I've read that there's some functionality, through

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

和Helper类的assetTimestamp方法。

and the assetTimestamp method of the Helper class.

现在,问题是:如何使用?

Now, the question is: How is it used?

我读取HtmlHelper代码,在css方法中, :

I read the HtmlHelper code and in the css method, line 361 there's this:

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


推荐答案

已解决。

首先,你必须考虑通过Apache。您可以查看本指南:
http://httpd.apache.org/docs/2.2 /caching.html

First of all you have to consider to make it through Apache. You can take a look at this guide: http://httpd.apache.org/docs/2.2/caching.html

事实是CakePHP有一个方法来做到这一点。很不错。

The thing is that CakePHP has a method to do this. And is pretty good.

我会解释这个CSS文件。当然也可以用于JS内容。

I'll explain this for CSS files. Of course can be used to JS content as well.

1)在您的core.php文件(在app / config /下)取消注释此行:

1) In your core.php file (under app/config/) uncomment this line:

Configure::write('Asset.filter.css', 'css.php');

这行说,CakePHP通过css.php脚本将所有请求路由到CSS文件。顾名思义,它是一个过滤器。我们可以做任何我们想要的。

That line says to CakePHP to route all requests to CSS files through that "css.php" script. As the name implies, it's a filter. There we can do whatever we want.

2)创建css.php文件。你必须在app / webroot /

2) Create that "css.php" file. You've to create it under app/webroot/

在那里,你可以获取browsen请求的文件,并应用一些缓存HTTP头。

Make there, you can take the file that the browsen is requesting and apply some cache HTTP headers.

类似:

$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/编程/ get-cakephp-build-in-css-compression-to-work /

还有一个很好的css.php版本,

There's a good version of css.php that also minfies it.

这篇关于如何在CakePHP2中缓存静态内容(css,images,js文件)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆