nepada/bust-cache

Cache busting Latte 标签。

v3.1.0 2023-09-28 17:04 UTC

README

Build Status Coverage Status Downloads this Month Latest stable

安装

通过 Composer

$ composer require nepada/bust-cache

config.neon 中注册扩展

extensions:
    bustCache: Nepada\Bridges\BustCacheDI\BustCacheExtension(%wwwDir%, %debugMode%)

可用配置选项及其默认值的概述

bustCache:
  strategy: contentHash # modificationTime in debugMode
  autoRefresh: %debugMode%
  manifest: true
  strictMode: false

如果你使用独立的 Latte,请手动安装 Latte 扩展

$fileSystem = Nepada\BustCache\LocalFileSystem::forDirectory($wwwDir);
$manifestFinder = new Nepada\BustCache\Manifest\AutodetectManifestFinder($fileSystem);
$revisionFinder = new Nepada\BustCache\Manifest\DefaultRevisionFinder($fileSystem, $manifestFinder);
$cache = new Nepada\BustCache\Caching\NullCache(); // or other implementation of Cache
$strategy = new Nepada\BustCache\CacheBustingStrategies\ContentHash(); // or other strategy
$pathProcessor = new Nepada\BustCache\BustCachePathProcessor($fileSystem, $cache, $revisionFinder, $strategy);
$latte->addExtension(new Nepada\Bridges\BustCacheLatte\BustCacheLatteExtension($pathProcessor, $strictMode, $autoRefresh));

用法

基本示例

<link rel="stylesheet" href="{bustCache /css/style.css}">

生成的路径取决于(自动)选择的缓存破坏策略

<!-- using path from revision manifest -->
<link rel="stylesheet" href="/css/style-30cc681d44.css">

<!-- using query cache busting with modificationTime strategy: timestamp of the last file modification -->
<link rel="stylesheet" href="/css/style.css?1449177985">

<!-- using query cache busting with contentHash strategy: first 10 letters of md5 hash of the file content -->
<link rel="stylesheet" href="/css/style.css?a1d0c6e83a">

在具有非平凡基本路径的应用程序中的用法

<link rel="stylesheet" href="{$basePath}{bustCache /css/style.css}">

生成完整绝对 URL

<link rel="stylesheet" href="{$baseUrl}{bustCache /css/style.css}">

修订版本清单支持

修订版本清单是一个 JSON 文件,其中包含原始资产路径与其修订路径之间的映射。

示例

{
    "css/style.css": "css/style-30cc681d44.css",
    "js/app.js": "js/app-68130ccd44.js"
}

配置

默认配置下,清单文件的路径通过从资产目录向上遍历并查找 manifest.jsonrev-manifest.json 来自动检测。如果找到清单文件,则使用其中包含的修订映射,而不是使用查询参数进行缓存破坏。

您可以通过在您的配置中设置 manifest: false 来完全禁用修订版本清单支持。

您还可以绕过自动检测并静态指定清单文件路径,例如 manifest: "assets/my-manifest.json"

缓存

缓存在运行时和编译时两个级别上实现。

运行时缓存

缓存存储每个输入路径的已计算缓存破坏路径。

如果已配置 nette/caching,DI 扩展将自动启用此缓存。在生产模式下使用默认设置,不会检查资产文件是否已修改以避免不必要的 I/O,即缓存不会自动刷新。

编译时缓存

当文件路径指定为字面字符串时,缓存破坏路径将在 Latte 模板编译时计算,并且缓存破坏路径将直接写入模板的编译代码中。

默认情况下,此功能仅在生产模式下启用。

修改应用程序运行时文件的缓存破坏

如果您希望在应用程序运行时预期会修改的文件上使用缓存破坏,则可以使用 dynamic 关键字退出编译时缓存,并在生产模式下强制刷新缓存。

<link rel="stylesheet" href="{bustCache dynamic /css/theme.css}">

处理缺失的清单或资产文件

默认配置下,当遇到缺失的文件(清单或资产)时,将触发警告并生成资产虚拟路径。您可以通过将 strictMode: true 切换到严格模式来通过抛出异常来失败。

"缺失文件"包括以下情况之一

  • 配置中指定的静态清单文件不存在
  • 清单文件指向一个不存在的修订路径
  • 使用查询参数进行缓存破坏,但资产路径不存在