Implemented custom CacheMiddleware

This commit is contained in:
Chris Kankiewicz
2021-06-19 23:53:09 -07:00
parent cb350de165
commit 72fa7e5621
3 changed files with 52 additions and 0 deletions

View File

@@ -96,4 +96,21 @@ return [
$config->get('redis_port')
);
}),
/**
* HTTP cache values for controlling browser page cache durations.
*
* Possible values: An array of content types mapped to their cache duration
* in seconds
*
* Default value: [
* 'application/json' => '300',
* 'application/zip' => '300',
* ]
*/
'http_cache' => [
'application/json' => '300',
'application/zip' => '300',
],
];

View File

@@ -23,6 +23,7 @@ return [
/** Array of application middlewares */
'middlewares' => function (ContainerInterface $container): array {
return [
Middlewares\CacheMiddleware::class,
Middlewares\ThemeMiddleware::class,
Middlewares\WhoopsMiddleware::class,
];

View File

@@ -0,0 +1,34 @@
<?php
namespace App\Middlewares;
use App\Config;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface as Request;
use Psr\Http\Server\RequestHandlerInterface as RequestHandler;
class CacheMiddleware
{
/** @var Config The application configuration */
protected $config;
/** Create a new CacheMiddleware. */
public function __construct(Config $config)
{
$this->config = $config;
}
/** Invoke the CacheMiddleware class. */
public function __invoke(Request $request, RequestHandler $handler): ResponseInterface
{
$response = $handler->handle($request);
foreach ($this->config->get('http_cache') as $contentType => $age) {
if (in_array($contentType, $response->getHeader('Content-Type'))) {
return $response->withHeader('Cache-Control', sprintf('max-age=%d', $age));
}
}
return $response->withHeader('Cache-Control', 'max-age=0, must-revalidate');
}
}