smartondev / httpcache
Simple HTTP cache management library
Installs: 13 141
Dependents: 1
Suggesters: 0
Security: 0
Stars: 1
Watchers: 1
Forks: 0
Open Issues: 0
Requires
- php: ^8.2
Requires (Dev)
- mockery/mockery: ^1.6
- pestphp/pest: ^3.7
- phpstan/phpstan: ^2.0
README
This package helps you to build HTTP cache headers like Cache-Control
, ETag
and matchers like If-None-Match
,
If-Modified-Since
. It is useful for building HTTP cache headers and matchers in your application.
Installation
composer require smartondev/httpcache
Usage
Cache headers
use SmartonDev\HttpCache\Builders\CacheHeaderBuilder; // max-age 1 hour, private, no-store $headers = (new CacheHeaderBuilder()) ->maxAge(hours: 1) ->private() ->noStore() ->toHeaders(); // max-age 60 sec, shared max age 120 sec, stale-while-revalidate 30 sec $headers = (new CacheHeaderBuilder()) ->maxAge(60) ->sharedMaxAge(120) ->staleWhileRevalidate(30) ->toHeaders();
No-cache
$noCacheHeaders = (new CacheHeaderBuilder()) ->noCache() ->toHeaders();
Durations
$builder = (new CacheHeaderBuilder()) ->maxAge(30) // 30 sec ->maxAge(seconds: 30) // 30 sec ->maxAge(minutes: 30) // 30 min ->maxAge(hours: 30) // 30 hours ->maxAge(days: 30) // 30 days ->maxAge(weeks: 30) // 30 weeks ->maxAge(months: 30) // 30 months ->maxAge(years: 30) // 30 years ->maxAge(days: 10, hours: 5, minutes: 30) // 10 days 5 hours 30 minutes
Etag check
use SmartonDev\HttpCache\Matchers\ETagMatcher; // ETag check $etagMatcher = (new ETagMatcher()) ->headers($requestHeaders); $activeEtag = '1234'; if($etagMatcher->matches($activeEtag)->matches()) { // 304 Not Modified return response(null, 304); }
Modified check
use SmartonDev\HttpCache\Matchers\ModifiedMatcher; // modified since $modifiedMatcher = (new ModifiedMatcher()) ->headers($requestHeaders); if($modifiedMatcher->matches($lastModified)->matchesModifiedAt()) { // 304 Not Modified return response(null, 304); }
Mutable and immutable accessors
with
prefixed methods are immutable, eg.withMaxAge()
. Methods withoutwith
prefix are mutable, eg.maxAge()
.without
prefixed methods are immutable, eg.withoutMaxAge()
. Methods withreset
prefix are mutable, eg.resetMaxAge()
.
$builderA = new CacheHeaderBuilder(); // mutable $builderA->maxAge(30) ->resetMaxAge(); // immutable $builderB = $builderA->withMaxAge(60); $builderC = $builderB->withoutMaxAge();
More documentation
- CacheHeaderBuilder: building cache headers like
Cache-Control
- ETagHeaderBuilder: building ETag header
- ETagMatcher: matching ETag headers like
If-Match
,If-None-Match
- ModifiedMatcher: matching modified headers like
If-Modified-Since
,If-Unmodified-Since
Contributing
Please see CONTRIBUTING for details.
License
This project is open-sourced software licensed under.