Created
December 14, 2015 21:45
-
-
Save adamgavlak/7d4e8f8acab1000da93f to your computer and use it in GitHub Desktop.
Laravel middleware for caching routes
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace App\Http\Middleware; | |
use Closure; | |
use Illuminate\Support\Facades\Cache; | |
class CacheOrRetrieve | |
{ | |
private $cacheTime = 10; | |
/** | |
* Handle an incoming request. | |
* | |
* @param \Illuminate\Http\Request $request | |
* @param \Closure $next | |
* @return mixed | |
*/ | |
public function handle($request, Closure $next) | |
{ | |
$key = $this->cacheKey($request->path()); | |
if (Cache::has($key)) { | |
$content = Cache::get($key); | |
$response = response($content); | |
if ($this->isJson($content)) { | |
$response->header('Content-Type', 'application/json'); | |
} | |
return $response; | |
} | |
$response = $next($request); | |
Cache::put($key, $response->getContent(), $this->cacheTime); | |
return $response; | |
} | |
private function isJson($string) { | |
json_decode($string); | |
return (json_last_error() == JSON_ERROR_NONE); | |
} | |
private function cacheKey($path) | |
{ | |
return 'route:' . str_replace('/', '-', $path); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment