tfountain/asset-path

简单的ZF2模块,用于资产版本控制

dev-master 2013-11-24 16:11 UTC

This package is not auto-updated.

Last update: 2024-09-24 06:21:49 UTC


README

此模块提供了一种简单的方法来对静态文件(图像、样式表、JavaScript等)进行版本控制,当与一些缓存友好的服务器配置结合使用时,可以提高您页面的渲染时间。

安装

安装此模块的最简单方法是使用Composer (https://getcomposer.org.cn/)。将以下内容添加到您的composer.json

"require": {
    "tfountain/asset-path": "dev-master"
}

然后更新您的应用程序的application.config.php以将TfAssetPath添加到您的模块数组中。

您还需要修改您的mod_rewrite规则,将版本化的资产请求重写为非版本化等效项。修改您的.htaccess文件(或虚拟主机),并在文件的最后重写块上方添加以下内容:

# Versioned assets
RewriteRule ^(images|js|css)/(([\w.-]+/)+)?([\w.-]+)\.[\w]+\.([\w]+)$ $1/$2$4.$5 [L]

所以如果您使用的是来自Zend Framework骨架应用程序的.htaccess文件,您修改后的.htaccess文件将看起来像这样

RewriteEngine On
# The following rule tells Apache that if the requested filename
# exists, simply serve it.
RewriteCond %{REQUEST_FILENAME} -s [OR]
RewriteCond %{REQUEST_FILENAME} -l [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^.*$ - [NC,L]

# Versioned assets
RewriteRule ^(images|js|css)/(([\w.-]+/)+)?([\w.-]+)\.[\w]+\.([\w]+)$ $1/$2$4.$5 [L]

# The following rewrites all other queries to index.php. The
# condition ensures that if you are using Apache aliases to do
# mass virtual hosting, the base path will be prepended to
# allow proper resolution of the index.php file; it will work
# in non-aliased environments as well, providing a safe, one-size
# fits all solution.
RewriteCond %{REQUEST_URI}::$1 ^(/.+)(.+)::\2$
RewriteRule ^(.*) - [E=BASE:%1]
RewriteRule ^(.*)$ %{ENV:BASE}index.php [NC,L]

(images|js|css)更改为包含一个用竖线分隔的静态文件文件夹列表,您可能想要在此模块上使用它(即您在public文件夹中的文件夹)。

为了看到任何好处,您需要使用未来很远的'Expires'标题来提供这些文件。如果您使用Apache,最简单的方法是使用mod_expires。要么修改您的虚拟主机(首选)为每个文件夹添加一个<Directory>

<Directory /path/to/public/css>
    <IfModule mod_expires.c>
        ExpiresActive On
        ExpiresByType text/css "access plus 60 days"
    </IfModule>
</Directory>

或者向该文件夹添加一个.htaccess文件

<IfModule mod_expires.c>
    ExpiresActive On
    ExpiresByType text/css "access plus 60 days"
</IfModule>

用法

该模块提供了一个视图助手,它将为给定的文件路径返回一个相同的路径,并在文件扩展名之前插入一个版本控制哈希。在您本应放置静态文件路径的情况下使用此助手,例如

<link rel="stylesheet" type="text/css" href="<?=$this->assetPath('/css/styles.css')?>">

这将输出

<link rel="stylesheet" type="text/css" href="/css/style.mwq02x.css">

(其中mwq02x是根据文件的最后修改时间生成的唯一哈希)。

假设您的过期标题已按上述建议设置,则浏览器将缓存此文件长达60天,并在用户浏览您的网站时不会重新请求它。但是,如果您修改了文件,哈希将自动更改,浏览器将其视为不同的文件并从服务器重新请求它。