bosi/content-cache

基于php、apache2和htaccess的内容缓存

0.3.0 2020-11-25 16:31 UTC

This package is auto-updated.

Last update: 2024-09-26 00:33:23 UTC


README

pipeline status

此包在文件系统级别提供了一种缓存机制,以实现快速缓存数据交付。

要求

  • composer(用于安装)
  • 至少php 7.3
  • apache2 网络服务器
  • 某种形式的cron定时清除缓存

安装

composer require bosi/content-cache

用法

  1. 在您的应用程序引导过程中初始化缓存
    <?php
    use Bosi\ContentCache\ContentCache;
    ContentCache::init('/absolute/path/to/webserver/root'); 
    
  2. 在渲染完整响应后添加缓存响应

     <?php
     use Bosi\ContentCache\ContentCache;
       
     // somewhere at the and of your controller (e.g. inside middleware before sending response to user)
     ContentCache::addToCache($response);
    
  3. 通过将以下行添加到您的 .htaccess 来启用您的apache网络服务器以提供缓存响应

     # prevent direct indexing of cache dir
     <If "%{THE_REQUEST} =~ /content-cache.+\.file/">
        Header set X-Robots-Tag "noindex, nofollow"
     </If>
        
     # handle cache for index page
     RewriteCond %{QUERY_STRING} ^$
     RewriteCond %{REQUEST_URI} ^/?$
     RewriteCond %{DOCUMENT_ROOT}/content-cache/__index.file -f
     RewriteRule .? content-cache/__index.file [L]
        
     # handle cache for non-index page
     RewriteCond %{QUERY_STRING} ^$
     RewriteCond %{DOCUMENT_ROOT}/content-cache%{REQUEST_URI}.file -f
     RewriteRule . content-cache%{REQUEST_URI}.file [L]
    
  4. 为您的系统添加一个cronjob以定时清除缓存,例如
    */5 * * * * rm -rf /absolute/path/to/webserver/root/content-cache/*
    

    如果您想使用php应用程序清除缓存,可以使用 ContentCache::clearCache()(第一个参数可以用来不刷新整个缓存)。

值得知道的是

  • 只有在找不到合适的缓存响应时,才会调用您的应用程序。
  • 此包在您定义的网络服务器根目录下创建一个名为 content-cache 的目录。所有缓存响应都保存在此目录中,如果您想清除特定路径的缓存,甚至可以删除单个文件/目录。
  • 带有URL查询参数的请求将不会缓存(也许以后我会将其作为一个功能添加,但目前存在一些问题)。
  • 除了查询参数之外,没有其他检查(例如状态码或HTTP方法)来决定是否缓存响应。您必须自己实现此类检查(例如,使用 ContentCache::init(...) 的第二个参数)。
  • 您可以直接查看 public/ 目录,以了解此包的完整用法示例(您甚至可以使用docker启动本地环境,并使用 make start 查看结果)。