生命周期 2--kernel 对象解析过程浅析
首先,$app已经创建完成,初始化工作也已经完成(具体步骤就不废话了)
- public/index.php
$app = require_once __DIR__.'/../bootstrap/app.php';
创建kernel对象
$kernel = $app->make(Illuminate\Contracts\Http\Kernel::class);
- 首先解析
Illuminate\Contracts\Http\Kernel::class
,返回其绑定时声明的闭包(由于绑定的时候是绑定的字符串,因此,这个闭包是\Illuminate\Container\Container::getClosure
返回的。实际上,就是去$app->make('App\Http\Kernel::class')。 -
解析
App\Http\Kernel::class
。由于没有绑定过它,因此是直接利用反射机制去生成对象。在生成对象的过程中,会去实例化反射对象的参数,如果参数生成的对象的构造函数中还有其他的类参数,那么就会递归的去实例化(这就是依赖注入的好处,否则光是写new就得累死)。过程就是:-
new \Illuminate\Foundation\Http\Kernel
public function __construct(Application $app, Router $router) { $this->app = $app; $this->router = $router; $router->middlewarePriority = $this->middlewarePriority; foreach ($this->middlewareGroups as $key => $middleware) { $router->middlewareGroup($key, $middleware); } foreach ($this->routeMiddleware as $key => $middleware) { $router->aliasMiddleware($key, $middleware); } }
- new \Illuminate\Routing\Router
public function __construct(Dispatcher $events, Container $container = null) { $this->events = $events; $this->routes = new RouteCollection; $this->container = $container ?: new Container; }
-
- 也就是说在这个
Illuminate\Contracts\Http\Kernel
解析过程中,实际上递归的解析了events, router, App\Http\Kernel,最后返回的是一个App\Http\Kernel
对象到$kernel
变量中。
本作品采用《CC 协议》,转载必须注明作者和本文链接
推荐文章: