2016年9月30日 星期五

使用中间件禁用浏览器缓存

我们想要在部分路由上完全禁用浏览器缓存,比如验证码,或者其它要求不能在浏览器端缓存的页面,我们可以建立如下一个中间件来完成:
app/Http/Middleware/NoHttpCache.php:
 namespace App\Http\Middleware;

use Closure;
use Illuminate\Contracts\Routing\Middleware;

use Illuminate\Http\Response;
use Symfony\Component\HttpFoundation\Response as SymfonyResponse;

class NoHttpCache implements Middleware {

    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $response = $next($request);

        // This step is only needed if you are returning
        // a view in your Controller or elsewhere, because
        // when returning a view `$next($request)` returns
        // a View object, not a Response object, so we need
        // to wrap the View back in a Response.
        if ( ! $response instanceof SymfonyResponse) {
            $response = new Response($response);
        }

        /**
         * @var  $headers  \Symfony\Component\HttpFoundation\HeaderBag
         */
        $response->header('Pragma', 'no-cache');
        $response->header('Expires', 'Fri, 01 Jan 1990 00:00:00 GMT');
        $response->header('Cache-Control', 'no-cache, must-revalidate, no-store, max-age=0, private');

        return $response;
    }
}
然后在 app/Http/Kernel.php 中 $routeMiddleware 中注册它就可以在路由中使用了:
...
use App\Http\Middleware\NoHttpCache;
...

/**
 * The application's route middleware.
 *
 * @var array
 */
protected $routeMiddleware = [
    'no_http_cache' => NoHttpCache::class,
];
在 routes.php 中对要禁用缓存的路由添加中间件:
Route::get('foo/bar', ['middleware' => 'no_http_cache', function () {
    // ...
}]);

from : http://laravel.so/tricks/e63b9350fa54e48e58f60a8e32c372d7

沒有留言:

wibiya widget