我正在尝试使用中间件缓存整个响应
我遵循的步骤
生成了两个中间件
- AfterCacheMiddleware
- BeforeCacheMiddleware
在 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 根本没有被调用
任何人都可以建议我在这里缺少什么吗?
最佳答案
我在自己寻找解决方案时发现了这个问题。我知道有 Flatten 包可以执行此缓存,但我找不到很好的示例来说明如何自己执行此操作。这个问题中的解决方案尝试包含对我自己的解决方案有用的想法,尽管我选择只使用一个中间件。
虽然这个问题很老,提问者可能不再需要答案了,但我会在这里分享我的解决方案,因为我觉得 SO(和互联网)缺少 Laravel 5 的缓存示例。我会尽量解释我可以,但为了最大的好处,您应该熟悉 Routing , Caching和 Middlewaring在 Laravel 5 中。所以这里是解决方案:
中间件
创建一个中间件,那些通常放在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');
});
关于php - 在 Laravel 5 中缓存整个 HTML 响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32880048/