具有各种缓存工具的中间件

v3.0.0 2023-12-17 13:08 UTC

This package is auto-updated.

Last update: 2024-09-17 14:42:32 UTC


README

Latest Version on Packagist Software License Testing Total Downloads

包含以下缓存工具的中间件组件

要求

安装

此包可通过 Composer 以 middlewares/cache 的方式安装和自动加载。

composer require middlewares/cache

CachePrevention

添加防止缓存的响应头。在开发环境中很有用

Dispatcher::run([
    new Middlewares\CachePrevention()
]);

Expires

此中间件将 ExpiresCache-Control: max-age 头添加到响应中。您可以配置每个 MIME 类型的缓存持续时间。如果没有定义,将使用默认值。

// Use the default configuration
$expires = new Middlewares\Expires();

// Custom durations
$expires = new Middlewares\Expires([
    'text/css' => '+1 year',
    'text/js' => '+1 week',
]);

defaultExpires

如果请求的 MIME 类型未配置,设置默认的过期值。默认为 1 个月。示例

//set 1 year lifetime to css and js
$durations = [
    'text/css' => '+1 year',
    'text/javascript' => '+1 year',
];

//and 1 hour to everything else
$default = '+1 hour';

$expires = (new Middlewares\Expires($durations))->defaultExpires($default);

Cache

将响应头保存到 PSR-6 缓存池 中,并在响应仍然有效(基于其 ETagLast-Modified 头)的情况下返回 304 响应(未修改)。这样可以节省服务器资源和带宽,因为返回的内容为空。建议将其与 Expires 结合使用,以设置响应的生存期。

$cachePool = new Psr6CachePool();

Dispatcher::run([
    new Middlewares\Cache($cachePool),
    new Middlewares\Expires()
]);

可选地,您可以将 Psr\Http\Message\ResponseFactoryInterface 作为第二个参数提供,以创建空的 304 响应。如果没有定义,将使用 Middleware\Utils\Factory 自动检测。

$cachePool = new Psr6CachePool();
$responseFactory = new MyOwnResponseFactory();

$cache = new Middlewares\Cache($cachePool, $responseFactory);

ClearSiteData

发送 Clear-Site-Data 头以从客户端(缓存、cookie、存储等)中删除所有站点数据

Dispatcher::run([
    new Middlewares\ClearSiteData()
]);

可选地,您可以为要清除的数据类型提供列表。

$cache = new Middlewares\ClearSiteData('cache', 'cookies');

有关最近更改的更多信息,请参阅 CHANGELOG,有关贡献的详细信息,请参阅 CONTRIBUTING

MIT 许可证 (MIT)。有关更多信息,请参阅 LICENSE