bosi / content-cache
A content cache based on php, apache2 and htaccess
0.3.0
2020-11-25 16:31 UTC
Requires
- php: >=7.3
Requires (Dev)
- phpunit/phpunit: ^9
This package is auto-updated.
Last update: 2024-09-26 00:33:23 UTC
README
This package provides a caching mechanism on file system level for super fast delivery of cached data.
Requirements
- composer (for installation)
- at least php 7.3
- apache2 webserver
- some kind of cron to clear cache from time to time
Installation
composer require bosi/content-cache
Usage
- Initialize the cache somewhere in your application bootstrapping
<?php use Bosi\ContentCache\ContentCache; ContentCache::init('/absolute/path/to/webserver/root');
Add cached responses after you have rendered the full response
<?php use Bosi\ContentCache\ContentCache; // somewhere at the and of your controller (e.g. inside middleware before sending response to user) ContentCache::addToCache($response);
Enable your apache webserver to serve cached responses by adding the following lines to your
.htaccess
# 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]
- Add a cronjon to your system to clear the cache from time to time e.g.
*/5 * * * * rm -rf /absolute/path/to/webserver/root/content-cache/*
If you want to clear the cache with your php app you can use
ContentCache::clearCache()
(first parameter can be used to not flush the complete cache).
Nice to know
- Your application is only called when no fitting cached response can be found.
- This package creates a directory called
content-cache
below you defined webserver root. All cached responses are saved inside this directory and you can even delete single files/directories if you want to clear cache for specific paths. - Requests with url query parameters will not be cached at all (maybe I'll at this later as a feature but currently ther're some problems with that).
- There are no further checks (execpt query params) against status code or http method to decide if a response should be cached. You have to implement such a check by yourself (e.g. by using the second param of
ContentCache::init(...)
. - You can have a look at the
public/
directly for a full example usage of this package (you can even start a local environment using docker andmake start
to view the result).