php 使用构造函数版本时未调用Laravel中间件终止

jv4diomz  于 2022-11-28  发布在  PHP
关注(0)|答案(1)|浏览(186)

Laravel版本:5.1.46
routes.php
Route::get('/rocha', 'RochaController@index');
Kernel.php

protected $routeMiddleware = [
        'auth' => \App\Http\Middleware\Authenticate::class,
        'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
        'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
        'Age' => \App\Http\Middleware\AgeMiddleware::class,
        'Role' => \App\Http\Middleware\RoleMiddleware::class,
    ];

RochaController.php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;

class RochaController extends Controller
{

    public function __construct() {
        $this->middleware('Role');
    }
    public function index() {
        echo '<br>Hi I am index';
    }
}

RochaMiddleware.php

namespace App\Http\Middleware;
use Closure;

class RoleMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        echo '<br>Hi I am middleware';
        return $next($request);
    }

    public function terminate($request, $response) {
        echo '<br>Shtting down...';
    }
}

结果:

Hi I am middleware
Hi I am index

当我在控制器中通过构造函数$this->middleware('Role')使用中间件时,terminate()函数没有被调用。当我切换代码取出控制器中的构造函数并将路径更改为以下路径时,terminate()函数被调用:

Route::get('/rocha', [
    'middleware' => 'Role',
    'uses' => 'RochaController@index'
]);

结果:

Hi I am middleware
Hi I am index
Shtting down...

为什么构造函数版本($this->middleware('Role'))阻止调用terminate()函数?
为什么路由版本可以工作,并且调用了terminate()函数,而不是上面的函数?

0g0grzrc

0g0grzrc1#

如果您在中间件上定义了一个终止方法,那么在响应准备好发送到浏览器之后,将自动调用该方法。
从终端中间件
我想你误解了terminate方法的用法。Laravel实际上调用了terminate方法,但浏览器不会显示terminate的输出。因为响应已经发送到浏览器。
可以使用此terminate方法测试调用是否成功。

public function terminate($request, $response)
{
    file_put_contents(__DIR__ . '/1.txt', 'hello terminate');
}

对了,我正在测试你的代码,它总是输出:

Hi I am middleware
Hi I am index

我也想知道为什么你能得到Shtting down...

相关问题