我正在尝试使用中间件缓存整个响应
我遵循的步骤
生成两个中间件
使用BeforeCacheMiddleware:
public function handle($request, Closure $next)
{
$key = $request->url();
if(Cache::has($key)) return Cache::get($key);
return $next($request);
}
使用AfterCacheMiddleware
public function handle ($request, Closure $next)
{
$response = $next($request);
$key = $request->url();
if (!Cache::has($key)) Cache::put($key, $response->getContent(), 60);
return $response;
}
在kernal.php的$ routeMiddleware数组中注册的中间件
'cacheafter' => 'App\Http\Middleware\AfterCacheMiddleware',
'cachebefore' => 'App\Http\Middleware\BeforeCacheMiddleware',
在routes.php中,我正在调用这样的虚拟路径
Route::get('middle', ['middleware' => 'cachebefore', 'cacheafter', function()
{
echo "From route";
}]);
问题:
仅调用 cachebefore 中间件。 cacheafter根本没有被调用
有谁可以建议我在这里缺少什么?
答案 0 :(得分:8)
我在寻找解决方案时发现了这个问题。我知道有Flatten包来做这个缓存,但是我找不到关于如何自己做这个的好例子。此问题中的解决方案尝试包含对我自己的解决方案有用的想法,尽管我选择仅使用单个中间件。
虽然问题很老,而且提问者可能不再需要答案了,但我会在这里分享我的解决方案,因为我觉得SO(和互联网)缺少Laravel 5的缓存样本。我会尽量解释我可以,但为了最大的好处,你应该熟悉Laravel 5中的Routing,Caching和Middlewaring。所以这里有解决方案:
创建一个中间件,这些通常放在app/Http/Middleware
文件夹中,我将调用文件CachePage.php
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Contracts\Auth\Guard;
use Cache;
class CachePage
{
public function handle($request, Closure $next)
{
$key = $request->fullUrl(); //key for caching/retrieving the response value
if (Cache::has($key)) //If it's cached...
return response(Cache::get($key)); //... return the value from cache and we're done.
$response = $next($request); //If it wasn't cached, execute the request and grab the response
$cachingTime = 60; //Let's cache it for 60 minutes
Cache::put($key, $response->getContent(), $cachingTime); //Cache response
return $response;
}
}
根据您的需要更改$key
...您拥有包含所有参数的所有$request
...如果要清除缓存,请将Cache::put($key, $value, $minutes)
更改为Cache::forever($key, $value)
手动,不希望它过期。
在大多数情况下,使用URL作为存储缓存的密钥是可用的,但有人可能会想到某个更适合某个项目的东西。
通过将中间件添加到app/Http/Kernel.php
数组,在$routeMiddleware
中注册它:
protected $routeMiddleware = [
/* ... */
/* Other middleware that you already have there */
/* ... */
'cachepage' => \App\Http\Middleware\CachePage::class,
];
当然,如果您将其放在别处或给它另一个名字,您应该更改\App\Http\Middleware\CachePage
。密钥名称cachepage
也取决于您 - 它将用于调用中间件。
例如,在app/Http/routes.php
使用中间件(例如auth
或其他中间件)时,您可以为应缓存的所有页面创建一个路由组:
Route::group(['middleware' => 'cachepage'], function ()
{
Route::get('/', 'HomeController@home');
Route::get('/contacts', 'SectionController@contacts');
});
答案 1 :(得分:0)
中间件列表必须在方括号内:
Route::get('middle', ['middleware' => ['cachebefore', 'cacheafter'], function()
{
echo "From route";
}]);