Laravel版本:5.1.46
routes.phpRoute::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()
函数,而不是上面的函数?
1条答案
按热度按时间0g0grzrc1#
如果您在中间件上定义了一个终止方法,那么在响应准备好发送到浏览器之后,将自动调用该方法。
从终端中间件
我想你误解了
terminate
方法的用法。Laravel实际上调用了terminate
方法,但浏览器不会显示terminate
的输出。因为响应已经发送到浏览器。可以使用此
terminate
方法测试调用是否成功。对了,我正在测试你的代码,它总是输出:
我也想知道为什么你能得到
Shtting down...