通过服务容器实例化App\Http\Kernel类时,这个类只是定义了$middleware(中间件)和$routeMiddleware(路由中间件)两个数组属性,其中中间件是请求进入路由处理前的处理类,而路由中间件是请求进入路由处理后的处理类,所以这里可以添加新的中间件处理类,只要按照中间件的设计原则进行设计,并在中间件数组的正确位置添加类名,在处理请求的过程中就会调用新添加的中间件处理过程。
Illuminate\Container\Container.php
/**
* Register a shared binding in the container.
*
* @param string|array $abstract
* @param \Closure|string|null $concrete
* @return void
*/
public function singleton($abstract, $concrete = null)
{
$this->bind($abstract, $concrete, true);
}
$app->singleton(
Illuminate\Contracts\Http\Kernel::class,
App\Http\Kernel::class
);
Illuminate\Foundation\Http\Kernel.php
//创建一个新的HTTP核心类实例
public function __construct(Application $app, Router $router)
{
$this->app = $app;
$this->router = $router;
foreach ($this->routeMiddleware as $key => $middleware) {
$router->middleware($key, $middleware);
}
}
Kernel类的构造函数是存在依赖的
Illuminate\Contracts\Foundation\Application
Illuminate\Routing\Router