笔记:中间件 middleware

中间件主要是提供了一种方便的机制用于过滤进入应用程序的 HTTP 请求。摘自文档
不仅可以过滤 HTTP 请求(前置中间件),也可用于记录日志(后置中间件),添加任务 (Terminable 中间件) 等。
命令行:php artisan make:middleware TestMiddleware
示例:

    public function handle($request, Closure $next)
    {
        //请求执行之前,过滤http请求
        Log::info('请求之前过滤http请求', []);

        $response = $next($request);

        //请求执行之后
        $response->header('Token', 'this is add token!');       //设置响应头的token
        $response->headers->set('Token1', 'this is add token1!');       //设置响应头的token
        $response->withHeaders([
            'Token2' => 'this is add token2!',
        ]);
        Log::info('controller return 之后', [1, 2, 3]);

        //响应
        return $response;
    }

基于 terminate 中间件实现慢请求日志:

    public function terminate($request, $response)
    {
        $slowRequest = config('request.slow_request_time');
        $useTime = microtime(true) - $_SERVER['REQUEST_TIME_FLOAT'];
        $log = [
            'url' => $request->url(),
            'method' => $request->method(),
            'path' => $request->path(),
            'headers' => $request->headers->all(),
            'params' => $request->all(),
            'clientIps' => $request->getClientIps()
        ];
        $info =  $request->path() . ' => userTime:' . $useTime * 1000 . 'ms';
        if ($slowRequest && $useTime > $slowRequest) {
            Log::channel('reqSlowLog')->info($info, $log);
        } else {
            Log::channel('reqLog')->info($info, $log);
        }
    }

配置文件 request.php 添加配置:

    // 慢请求日志时间
    'slow_request_time' => env('SLOW_REQUEST_TIME', 0),
本作品采用《CC 协议》,转载必须注明作者和本文链接
《L05 电商实战》
从零开发一个电商项目,功能包括电商后台、商品 & SKU 管理、购物车、订单管理、支付宝支付、微信支付、订单退款流程、优惠券等
《L02 从零构建论坛系统》
以构建论坛项目 LaraBBS 为线索,展开对 Laravel 框架的全面学习。应用程序架构思路贴近 Laravel 框架的设计哲学。