Skip to content

Instantly share code, notes, and snippets.

@rodrigopedra
Last active February 11, 2016 06:02
Show Gist options
  • Save rodrigopedra/cc66abb656d79cc1d311 to your computer and use it in GitHub Desktop.
Save rodrigopedra/cc66abb656d79cc1d311 to your computer and use it in GitHub Desktop.
Laravel Russian Doll Caching
<?php
namespace App\Providers;
use Blade;
use Illuminate\Support\ServiceProvider;
class AppServiceProvider extends ServiceProvider
{
/**
* Bootstrap any application services.
*
* @return void
*/
public function boot()
{
Blade::directive( 'cache', function ( $expression ) {
return "<?php echo \\App\\Services\\RussianDollCaching::get{$expression}; ?>";
} );
}
/**
* Register any application services.
*
* @return void
*/
public function register()
{
//
}
}
<?php
namespace App\Services;
use Cache;
use InvalidArgumentException;
use Illuminate\Database\Eloquent\Model;
class RussianDollCaching
{
public static function get( $view, array $data )
{
$model = reset( $data );
if (!$model instanceof Model) {
throw new InvalidArgumentException;
}
$key = join( '/', [ md5( $view ), get_class( $model ), $model->id, $model->updated_at->timestamp ] );
return Cache::tags( 'views' )->rememberForever( $key, function () use ( $view, $data ) {
return view( $view, $data )->render();
} );
}
}
@rodrigopedra
Copy link
Author

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