Last active
January 5, 2017 10:11
-
-
Save joshbrw/6ddf41715cc3833eb64efb94543468a1 to your computer and use it in GitHub Desktop.
Repository Cache Decoration
This file contains hidden or 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 | |
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(); | |
}); | |
} | |
} |
This file contains hidden or 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 | |
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(); | |
} | |
} |
This file contains hidden or 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 | |
interface UserRepository { | |
/** | |
* Create a new User in persistence | |
* @return mixed | |
*/ | |
public function create(); | |
/** | |
* Get all Users | |
* @return Collection | |
*/ | |
public function all(); | |
} |
This file contains hidden or 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 | |
/* 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