Skip to content

Instantly share code, notes, and snippets.

@dwightwatson
Created January 20, 2016 23:17
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save dwightwatson/5f7e46ca931591a807f9 to your computer and use it in GitHub Desktop.
Save dwightwatson/5f7e46ca931591a807f9 to your computer and use it in GitHub Desktop.
A simple cache middleware for Laravel 5, which won't cache authenticated pages.
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Contracts\Auth\Guard;
use Illuminate\Contracts\Cache\Repository;
class Cache
{
/**
* The Guard implementation.
*
* @var \Illuminate\Contracts\Auth\Guard
*/
protected $auth;
/**
* The cache implementation.
*
* @var \Illuminate\Contracts\Cache\Repository
*/
protected $cache;
/**
* The number of minutes to cache the response.
*
* @var int
*/
protected $minutes = 60;
/**
* Create a new filter instance.
*
* @param \Illuminate\Contracts\Auth\Guard $auth
* @param \Illuminate\Contracts\Cache\Repository $cache
* @return void
*/
public function __construct(Guard $auth, Repository $cache)
{
$this->auth = $auth;
$this->cache = $cache;
}
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
$cacheKey = $this->getCacheKey($request);
if ($this->isCacheEligible($cacheKey) && $this->cacheExists($cacheKey)) {
return $this->cache->get($cacheKey);
}
return $next($request);
}
/**
* Determine whether a cached item already exists.
*
* @param string
* @return bool
*/
protected function cacheExists($cacheKey)
{
return $this->cache->has($cacheKey);
}
/**
* Determine whether the cache is eligible to be used.
*
* @param string $cacheKey
* @return bool
*/
protected function isCacheEligible($cacheKey)
{
return $this->auth->guest();
}
/**
* Get the cache key for the request.
*
* @param \Illuminate\Http\Request $request
* @return string
*/
protected function getCacheKey(Request $request)
{
return str_slug("route-{$request->url()}");
}
/**
* Perform any final actions for the request lifecycle.
*
* @param \Illuminate\Http\Request $request
* @param \Illuminate\Http\Response $response
* @return void
*/
public function terminate($request, $response)
{
$cacheKey = $this->getCacheKey($request);
if ($this->isCacheEligible($cacheKey)) {
$this->cache->put($cacheKey, $response->getContent(), $this->minutes);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment