Created
April 2, 2014 13:05
-
-
Save zofe/9933671 to your computer and use it in GitHub Desktop.
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 Zofe\Filters; | |
/* | |
my customized version of jeff class https://laracasts.com/lessons/caching-essentials | |
*/ | |
use Illuminate\Routing\Route; | |
use Illuminate\Http\Request; | |
use Illuminate\Http\Response; | |
use Str; | |
use Cache; | |
use View; | |
/* | |
usage in filters: | |
Route::group(array('before' =>'cache.fetch', 'after' => array('cache.put','cache.finish')), function() | |
{ | |
.. | |
} | |
usage in views: | |
<view source="path.to.uncached.view" /> | |
*/ | |
class CacheFilter { | |
public function fetch(Route $route, Request $request) | |
{ | |
$key = $this->makeCacheKey($request->url()); | |
if (Cache::has($key)) return Cache::get($key); | |
} | |
public function put(Route $route, Request $request, Response $response) | |
{ | |
$key = $this->makeCacheKey($request->url()); | |
if (!Cache::has($key)){ | |
Cache::put($key, $response->getContent(), 5); //cache for n minutes | |
} | |
} | |
public function finish(Route $route, Request $request, Response $response) | |
{ | |
$content = $response->getContent(); | |
if (preg_match_all("#<view source=\"([A-Za-z0-9/_.-]+)\" \/>#iU", $content, $matches)) | |
{ | |
foreach (array_keys($matches[0]) as $id) | |
{ | |
$view = $matches[1][$id]; | |
if (View::exists($view)) | |
{ | |
$partial = (string)View::make($view); | |
$content = str_replace($matches[0][$id], $partial, $content); | |
} | |
} | |
} | |
$response->setContent($content); | |
} | |
protected function makeCacheKey($url) | |
{ | |
return 'route_'.Str::slug($url); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment