Last active
June 15, 2018 07:30
-
-
Save yoyosan/943c85fb0adfa322f8fa1615d833b679 to your computer and use it in GitHub Desktop.
Object Caching using Decorators
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 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