Skip to content

smartondev/httpcache

Repository files navigation

Build HTTP cache headers, ETag and modified matchers

GitHub Release GitHub License PHPUnit - GitHub Actions PHPStan level 10 - GitHub Actions Coverage Status Codecov

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 without with prefix are mutable, eg. maxAge().
  • without prefixed methods are immutable, eg. withoutMaxAge(). Methods with reset prefix are mutable, eg. resetMaxAge().
$builderA = new CacheHeaderBuilder();
// mutable
$builderA->maxAge(30)
         ->resetMaxAge();

// immutable
$builderB = $builderA->withMaxAge(60);
$builderC = $builderB->withoutMaxAge();

More documentation

Contributing

Please see CONTRIBUTING for details.

License

This project is open-sourced software licensed under.

Author

About

Native PHP library for HTTP cache header management

Topics

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages