我的每个控制器的__construct方法都有一个缓存每个公共控制器请求的HTML输出的中间件设置。
public function __construct() {
$this->middleware('auth', ['except' => ['index', 'show']]);
$this->middleware('cache.get', ['only' => 'show']);
$this->middleware('cache.put', ['only' => 'show']);
}
缓存工作正常,正如预期的那样,除了一件事:我在RouteServiceProvider.php中设置了Route-Model绑定,以便在各自的控制器中轻松访问模型,例如
public function boot(Router $router)
{
parent::boot($router);
$router->bind('posts', function($id) {
return \App\Article::findBySlugOrIdOrFail($id);
});
$router->bind('tags', function($name) {
return \App\Tag::where('name', $name)->firstOrFail();
});
$router->bind('artists', function($slug) {
return \App\Artist::findBySlugOrIdOrFail($slug);
});
基本上正在发生的事情是,即使页面被缓存,我仍然会查找每个路径的单个查询,其中它正在查找slug(SluggableInterface)或id。想知道是否有办法在缓存路由时不进行查询?或者这是不可能的?
谢谢!
修改
这是我的缓存中间件:
class GetCache
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
$key = StringHelper::keygen($request->path());
if (Cache::has($key) && Auth::guest()) {
$content=Cache::get($key);
return response($content);
}
return $next($request);
}
}
class PutCache
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
$response = $next($request);
$key = StringHelper::keygen($request->path());
if (! Cache::has($key) && Auth::guest()) {
Cache::put($key, $response->getContent(), 600);
}
return $next($request);
}
}