Skip to content

Instantly share code, notes, and snippets.

@joshbrw
Last active January 5, 2017 10:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save joshbrw/6ddf41715cc3833eb64efb94543468a1 to your computer and use it in GitHub Desktop.
Save joshbrw/6ddf41715cc3833eb64efb94543468a1 to your computer and use it in GitHub Desktop.
Repository Cache Decoration
<?php
class CacheUserRepositoryDecorator implements UserRepository {
protected $userRepository;
protected $cache;
protected $cacheTag = 'users';
public function __construct(UserRepository $userRepository)
{
$this->userRepository = $userRepository;
$this->cache = app('cache');
}
/**
* Create a new User in persistence
* @return mixed
*/
public function create()
{
if ($user = $this->userRepository->create()) {
/* Flush cache tag upon creation of a new user.
You'd also flush on update, deletion, etc. */
$this->cache->tags($this->cacheTag)->flush();
return $user;
}
return null;
}
/**
* Get all Users
* @return Collection
*/
public function all()
{
return $this->cache->remember(120, function () {
return $this->userRepository->all();
});
}
}
<?php
class EloquentUserRepository implements UserRepository {
/**
* Create a new User in persistence
* @return mixed
*/
public function create()
{
$user = User::create();
return $user;
}
/**
* Get all Users
* @return Collection
*/
public function all()
{
return User::query()->get();
}
}
<?php
interface UserRepository {
/**
* Create a new User in persistence
* @return mixed
*/
public function create();
/**
* Get all Users
* @return Collection
*/
public function all();
}
<?php
/* In the Service Provider */
$this->app->bind(UserRepository::class, function ($app) {
return new CacheUserRepositoryDecorator($app->make(EloquentUserRepository::class));
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment