Skip to content

Instantly share code, notes, and snippets.

@yoyosan
Last active June 15, 2018 07: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 yoyosan/943c85fb0adfa322f8fa1615d833b679 to your computer and use it in GitHub Desktop.
Save yoyosan/943c85fb0adfa322f8fa1615d833b679 to your computer and use it in GitHub Desktop.
Object Caching using Decorators
<?php
// in App\Repo\Topic.php
interface Topic
{
public function topics();
}
// in App\Repo\TopicQuery.php
use App\Topic as TopicModel;
class TopicQuery implements Topic
{
public function topics()
{
return TopicModel::with([
'series',
'series.content',
])->get();
}
}
// In App\Providers\AppServiceProvider.php
// ...
public method register()
{
$this->app->singleton(Topic::class, function() {
return new TopicQuery();
});
}
// ...
// In App\Http\Controllers\TopicController.php
use App\Repo\Topic;
class TopicController extends Controller
{
public function index(Topic $topic)
{
return view('topic', [
'topics' => $topic->topics(),
]);
}
}
//////////////////////
// Now with caching //
//////////////////////
// in App\Repo\TopicCache.php
use Cache;
class TopicCache implements Topic
{
protected $next;
public function __construct(Topic $next)
{
$this->next = $next;
}
public function topics()
{
return Cache::remember(60, 'topics', function() {
$this->next->topics();
});
}
}
// In App\Providers\AppServiceProvider.php
// ...
public method register()
{
$this->app->singleton(Topic::class, function() {
if (config('cache.enabled')) {
return new TopicCache(new TopicQuery);
}
return new TopicQuery;
});
}
// ...
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment