Skip to content

Instantly share code, notes, and snippets.

@richthegeek
Created March 8, 2012 16:24
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save richthegeek/2001903 to your computer and use it in GitHub Desktop.
Save richthegeek/2001903 to your computer and use it in GitHub Desktop.
Variable microcaching with Laravel
<?php
Route::filter('cache', function($response = NULL) {
$cname = 'response-' . Str::slug(URI::full());
if (!$response) {
return Cache::get($cname);
}
else if ($response->status == 200) {
$ctime = floor(pow(current(sys_getloadavg()) + 1, 5)); # cache for between 1 and 32 minutes
Cache::put($cname, $response, $ctime);
}
});
<?php
Route::get('foo', array('before' => 'cache', 'after' => 'cache', function() {
...
});
@Idered
Copy link

Idered commented Mar 9, 2012

    elseif ($response->status == 200)) {
        $ctime = floor(pow(current(sys_getloadavg()) + 1, 5)); # cache for between 1 and 32 minutes
        Cache::put($cname, $response, $ctime);
    }

:)

@richthegeek
Copy link
Author

Indeed - the response status guard was added slightly later so I never thought to merge the two!

@maikeldaloo
Copy link

So, this snippet caches the full page/reponse based on how long it takes to load.
Is that right?

@richthegeek
Copy link
Author

maikeldaloo: not quite, it caches the full response based on how busy the server is at the time.

However, factoring in page build time isn't such a bad idea!

@maikeldaloo
Copy link

That's really cool.

@maikeldaloo
Copy link

Just noticed a tiny bug when developing locally on a Windows machine, and possibly if the site is hosted on a Windows machine.

Windows doesn't allow semicolons (:) in file names.
It's better to use a dash or an underscore.

@richthegeek
Copy link
Author

Solution: don't develop on windows ;)

I've update the gist to fix this anyway.

@maikeldaloo
Copy link

Haha, I love my Windows :)
Thanks.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment