Many people do this differently but when best practices is a concern I believe the best place to do caching is in your repository.
Your controller shouldn't know too much about the data source I mean whether its coming from cache or coming from database.
Caching in controller doesn't support DRY (Don't Repeat Yourself) approach, because you find yourself duplicating your code in several controllers and methods thereby making scripts difficult to maintain.
So for me this is how I roll in Laravel 5 not so different if are using laravel 4:
//1. Create GalleryEloquentRepository.php in App/Repositories
<?php namespace AppRepositories;
use AppModelsGallery;
use Cache;
/**
* Class GalleryEloquentRepository
* @package AppRepositories
*/
class GalleryEloquentRepository implements GalleryRepositoryInterface
{
public function all()
{
return Cache::remember('gallerys', $minutes='60', function()
{
return Gallery::all();
});
}
public function find($id)
{
return Cache::remember("gallerys.{$id}", $minutes='60', function() use($id)
{
if(Cache::has('gallerys')) return Cache::has('gallerys')->find($id); //here am simply trying Laravel Collection method -find
return Gallery::find($id);
});
}
}
//2. Create GalleryRepositoryInterface.php in App/Repositories
<?php namespace AppRepositories;
/**
* Interface GalleryRepositoryInterface
* @package AppRepositories
*/
interface GalleryRepositoryInterface
{
public function find($id);
public function all();
}
//3. Create RepositoryServiceProvider.php in App/Providers
<?php namespace AppProviders;
use IlluminateSupportServiceProvider;
/**
* Class RepositoryServiceProvider
* @package AppProviders
*/
class RepositoryServiceProvider extends ServiceProvider
{
/**
* Indicates if loading of the provider is deferred.
*
* @var bool
*/
//protected $defer = true;
/**
* Bootstrap the application services.
*
* @return void
*/
public function boot()
{
//
}
/**
* Register the application services.
*
* @return void
*/
public function register()
{
$this->app->bind(
'AppRepositoriesGalleryRepositoryInterface',
'AppRepositoriesGalleryEloquentRepository'
);
}
}
//4. At the controller you can do this
<?php namespace AppHttpControllers;
use View;
use AppRepositoriesGalleryRepositoryInterface;
class GalleryController extends Controller {
public function __construct(GalleryRepositoryInterface $galleryInterface)
{
$this->galleryInterface = $galleryInterface;
}
public function index()
{
$gallery = $this->galleryInterface->all();
return $gallery ? Response::json($gallery->toArray()) : Response::json($gallery,500);
}
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…