|
| 1 | +# HTTP Cache - `smartondev/httpcache` |
| 2 | + |
| 3 | +**This code is under development and not ready for production use.** |
| 4 | + |
| 5 | +## Installation |
| 6 | + |
| 7 | +```bash |
| 8 | +composer require smartondev/httpcache |
| 9 | +``` |
| 10 | + |
| 11 | +## Usage |
| 12 | + |
| 13 | +```php |
| 14 | +use Smartondev\HttpCache\CacheHeaderBuilder; |
| 15 | +use Smartondev\HttpCache\ETagHeaderBuilder; |
| 16 | +use Smartondev\HttpCache\ETagMatcher; |
| 17 | +use SmartonDev\HttpCache\ModifiedMatcher; |
| 18 | + |
| 19 | +// max-age 30 day, private, no-store |
| 20 | +$headers = (new CacheHeaderBuilder()) |
| 21 | + ->withMaxAge(hours: 30) |
| 22 | + ->withPrivate() |
| 23 | + ->withNoStore() |
| 24 | + ->toHeaders(); |
| 25 | + |
| 26 | +// max-age 60 sec, shared max age 120 sec, stale-while-revalidate 30 sec |
| 27 | +$headers = (new CacheHeaderBuilder()) |
| 28 | + ->withMaxAge(60) |
| 29 | + ->withSharedMaxAge(120) |
| 30 | + ->withStaleWhileRevalidate(30) |
| 31 | + ->toHeaders(); |
| 32 | + |
| 33 | +// etag |
| 34 | +$etagMatcher = (new ETagMatcher()) |
| 35 | + ->withHeaders($requestHeaders); |
| 36 | +$etagHeaderBuilder = (new ETagHeaderBuilder()) |
| 37 | + ->withComputedEtag() |
| 38 | +if($etagMatcher->matches($etag)->matches()) { |
| 39 | + // 304 Not Modified |
| 40 | + return response(null, 304); |
| 41 | +} |
| 42 | + |
| 43 | +// modified since |
| 44 | +$modifiedMatcher = (new ModifiedMatcher()) |
| 45 | + ->withHeaders($requestHeaders); |
| 46 | +if($modifiedMatcher->matches($lastModified)->isBeforeModifiedSince()) { |
| 47 | + // 304 Not Modified |
| 48 | + return response(null, 304); |
| 49 | +} |
| 50 | +``` |
| 51 | + |
| 52 | +... |
| 53 | + |
| 54 | +### Durations |
| 55 | + |
| 56 | +```php |
| 57 | +$headers = (new CacheHeaderBuilder()) |
| 58 | + ->withMaxAge(30) // 30 sec |
| 59 | + ->withMaxAge(seconds: 30) // 30 sec |
| 60 | + ->withMaxAge(minutes: 30) // 30 min |
| 61 | + ->withMaxAge(hours: 30) // 30 hours |
| 62 | + ->withMaxAge(days: 30) // 30 days |
| 63 | + ->withMaxAge(weeks: 30) // 30 weeks |
| 64 | + ->withMaxAge(months: 30) // 30 months |
| 65 | + ->withMaxAge(years: 30) // 30 years |
| 66 | + ->withMaxAge(days: 10, hours: 5, minutes: 30) // 10 days 5 hours 30 minutes |
| 67 | + ->toHeaders(); |
| 68 | +``` |
| 69 | + |
| 70 | +... |
| 71 | + |
| 72 | +## Author |
| 73 | + |
| 74 | +- [Márton Somogyi](https://github.com/kamarton) |
0 commit comments