Skip to content

Instantly share code, notes, and snippets.

@joshbrw
Created April 21, 2017 21:30
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/30d17fc1fae73f05dcb24eb030cc4f54 to your computer and use it in GitHub Desktop.
Save joshbrw/30d17fc1fae73f05dcb24eb030cc4f54 to your computer and use it in GitHub Desktop.
<?php
interface UserFetcher {
/**
* Fetch a User by it's ID
* @param $id
* @return mixed
*/
public function fetch($id);
}
class EloquentUserFetcher implements UserFetcher {
/**
* Fetch a User by it's ID
* @param $id
* @return mixed
*/
public function fetch($id)
{
return User::find($id);
}
}
class CacheUserFetcherDecorator implements UserFetcher {
/**
* @var UserFetcher
*/
protected $fetcher;
public function __construct(UserFetcher $fetcher)
{
$this->fetcher = $fetcher;
}
/**
* Fetch a User by it's ID
* @param $id
* @return mixed
*/
public function fetch($id)
{
return cache()->get("user-{$id}", function () use ($id) {
return $this->fetcher->fetch($id);
});
}
}
$fetcher = new CacheUserFetcherDecorator(new EloquentUserFetcher);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment