PHP code example of methorz / http-cache-middleware
1. Go to this page and download the library: Download methorz/http-cache-middleware library. Choose the download type require.
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
methorz / http-cache-middleware example snippets
use MethorZ\HttpCache\Middleware\CacheMiddleware;
// Add to middleware pipeline
$app->pipe(new CacheMiddleware());
use MethorZ\HttpCache\Middleware\CacheMiddleware;
use MethorZ\HttpCache\Directive\CacheControlDirective;
$cacheControl = CacheControlDirective::create()
->public()
->maxAge(3600)
->mustRevalidate();
$middleware = new CacheMiddleware(cacheControl: $cacheControl);
// For images, CSS, JS with content hashing in filename
$middleware = new CacheMiddleware(
cacheControl: CacheControlDirective::create()
->public()
->maxAge(31536000) // 1 year
->immutable(),
);
// Cache API responses for 5 minutes
$middleware = new CacheMiddleware(
cacheControl: CacheControlDirective::create()
->public()
->maxAge(300)
->mustRevalidate(),
);
// Always validate with server, but use weak ETags
$middleware = new CacheMiddleware(
useWeakEtag: true,
cacheControl: CacheControlDirective::create()
->public()
->noCache() // Always revalidate
->maxAge(0),
);
// Cache in browser only, not in shared caches
$middleware = new CacheMiddleware(
cacheControl: CacheControlDirective::create()
->private()
->maxAge(300),
);
// Different cache times for browser vs CDN
$middleware = new CacheMiddleware(
cacheControl: CacheControlDirective::create()
->public()
->maxAge(300) // Browser: 5 minutes
->sMaxAge(3600) // CDN: 1 hour
->staleWhileRevalidate(60),
);
// config/autoload/middleware.global.php
use MethorZ\HttpCache\Middleware\CacheMiddleware;
use MethorZ\HttpCache\Directive\CacheControlDirective;
return [
'dependencies' => [
'factories' => [
CacheMiddleware::class => function (): CacheMiddleware {
return new CacheMiddleware(
cacheControl: CacheControlDirective::create()
->public()
->maxAge(3600),
);
},
],
],
];
// config/pipeline.php
$app->pipe(CacheMiddleware::class);
// Apply different caching strategies per route
$publicCaching = new CacheMiddleware(
cacheControl: CacheControlDirective::create()->public()->maxAge(3600),
);
$privateCaching = new CacheMiddleware(
cacheControl: CacheControlDirective::create()->private()->maxAge(300),
);
$app->get('/api/public', [$publicCaching, PublicHandler::class]);
$app->get('/api/user/profile', [$privateCaching, ProfileHandler::class]);
// ❌ Don't cache sensitive user data publicly
CacheControlDirective::create()->public(); // Bad for /api/user/profile
// ✅ Use private for user-specific data
CacheControlDirective::create()->private(); // Good for /api/user/profile
Loading please wait ...
Before you can download the PHP files, the dependencies should be resolved. This can take some minutes. Please be patient.