laravel源码分析
目录
laravel底层分析
一、生命周期
二、运行原理概述
三、详细源码分析
laravel底层分析
一、生命周期
二、运行原理概述
laravel的入口文件 public/index.php
1、引入自动加载 autoload.php
2、创建应用实例,并同时完成了:
- 基本绑定($this、容器类Container等等)
- 基本服务提供者的注册(Event、log、routing)
- 核心类别名的注册(比如app、db、auth、config、router等)
3、开始Http请求的处理
make
方法从容器中解析指定的值为实际的类,比如$app>make(Illuminate\\Contracts\\Http\\Kernel::class)
解析出App\\Http\\Kernel::class
->handle
方法对http
请求进行处理- 实际上是
handle
中的sendRequestThroughRouter
处理的http
请求 - 首先,将
request
绑定到共享实例 ,执行$this->bootstrap()
方法,运行给定的引导类数组$bootstrappers
,这里很关键,包括了加载配置文件、环境变量、服务提供者(config/app.php
中的providers
)、门面、异常处理、引导提供者 - 进入
Pipeline
管道类,经过全局中间件的处理过滤后,再进行执行Router类的dispatchToRouter
(用户请求的分发) - 在
dispatchToRoute
请求分发时,首先,findRoute
查找与给定请求匹配的路由,路由匹配match
然后执行runRoute
方法,实际处理请求的是runRoute
方法中的runRouteWithinStack
,并执行路由组中间件以及路由中间件 - 经过
runRouteWithinStack
中的run
方法,判断isControllerAction
将请求分配到实际的控制器中runController
或者执行runCallable
,并得到响应结果
4、将处理结果返回
$this->prepareResponse
方法返回了 Reqponse 实例,响应由Symfony\Component\HttpFoundation\Response实现
$response->send();
将响应数据返回给客户端
send 中将设置好的那些 headers 设置到 HTTP 的头部字段中,然后将 Content 输出到 HTTP 的实体中,最后通过 PHP 将完整的 HTTP 响应发送给客户
5 、执行请求生命周期的所有最终操作
$kernel->terminate($request, $response);
最后是 terminate 逻辑的调用,Laravel 中间件会检查全局中间件和路由中间件中是否包含 trminate 方法,如果包含的话则认为改中间件为 终端中间件,并执行其中的 terminate 方法。
三、详细源码分析
1、注册自动加载器,实现文件的自动加载
require __dir__.'/../vendor/autoload.php';
2、创建应用容器实例Application(该实例继承自容器类Container),并绑定核心(web、命令行、异常),以便在需要时解析它们
$app = require_once __DIR__.'/../bootstrap/app.php';
app.php文件如下:
<?php
// 创建Laravel实例 【3】
$app = new Illuminate\\Foundation\\Application($_ENV['APP_BASE_PATH'] ?? dirname(__DIR__)
);
// 绑定Web端kernel
$app->singleton(Illuminate\\Contracts\\Http\\Kernel::class,App\\Http\\Kernel::class
);
// 绑定命令行kernel
$app->singleton(Illuminate\\Contracts\\Console\\Kernel::class,App\\Console\\Kernel::class
);
// 绑定异常处理kernel
$app->singleton(Illuminate\\Contracts\\Debug\\ExceptionHandler::class,App\\Exceptions\\Handler::class
);
// 返回应用实例
return $app;
3、在创建应用实例(Application.php)的构造函数中,将基本绑定注册到容器中,并注册了所有的基本服务提供者,以及在容器中注册核心类别名
public function __construct($basePath = null)
{// 将基本绑定注册到容器中【3.1】$this->registerBaseBindings();// 注册所有基本服务提供者【3.2】$this->registerBaseServiceProviders();// 在容器中注册核心类别名【3.3】$this->registerCoreContainerAliases();
}
3.1、将基本绑定注册到容器中
static::setInstance($this);$this->instance('app', $this);$this->instance(Container::class, $this);$this->singleton(Mix::class);$this->instance(PackageManifest::class, new PackageManifest(new Filesystem, $this->basePath(), $this->getCachedPackagesPath()));# 注:instance方法为将...注册为共享实例,singleton方法为将...注册为共享绑定
3.2、注册所有基本服务提供者(事件、日志、路由)
protected function registerBaseServiceProviders()
{$this->register(new EventServiceProvider($this));$this->register(new LogServiceProvider($this));$this->register(new RoutingServiceProvider($this));
}
3.3、在容器中注册核心类别名
4、上面完成了类的自动加载、服务提供者注册、核心类的绑定、以及基本注册的绑定
5、开始解析http请求
index.php
// 5.1
$kernel = $app->make(Illuminate\\Contracts\\Http\\Kernel::class);
// 5.2
$response = $kernel->handle(
// 根据 Symfony 的 request 对象封装出 Illuminate\\Http\\Request$request = Illuminate\\Http\\Request::capture()
);
5.1 make方法是从容器解析给定值
$kernel = $app->make(Illuminate\\Contracts\\Http\\Kernel::class);
中的Illuminate\\Contracts\\Http\\Kernel::class
是在index.php 中的
$app = require_once __DIR__.'/../bootstrap/app.php';
这里面进行绑定的,
实际指向的就是App\\Http\\Kernel::class
这个类 5.2 这里对http请求进行处理
$response = $kernel->handle($request = Illuminate\\Http\\Request::capture()
);
进入$kernel所代表的类App\Http\Kernel.php中,我们可以看到其实里面只是定义了一些中间件相关的内容,并没有handle方法
我们再到它的父类use Illuminate\\Foundation\\Http\\Kernel as HttpKernel;
中找handle方法,可以看到handle方法是这样的
public function handle($request)
{try {$request->enableHttpMethodParameterOverride();// 最核心的处理http请求的地方【6】$response = $this->sendRequestThroughRouter($request);} catch (Exception $e) {$this->reportException($e);$response = $this->renderException($request, $e);} catch (Throwable $e) {$this->reportException($e = new FatalThrowableError($e));$response = $this->renderException($request, $e);}$this->app['events']->dispatch(new Events\\RequestHandled($request, $response));return $response;
}
6、处理http请求(将request绑定到共享实例,并使用管道模式处理用户请求)
vendor/laravel/framework/src/Illuminate/Foundation/Http/Kernel.php的handle方法
// 最核心的处理http请求的地方
$response = $this->sendRequestThroughRouter($request);
进入sendRequestThroughRouter方法
protected function sendRequestThroughRouter($request)
{// 将请求$request绑定到共享实例$this->app->instance('request', $request);// 将请求request从已解析的门面实例中清除(因为已经绑定到共享实例中了,没必要再浪费资源了)Facade::clearResolvedInstance('request');// 引导应用程序进行HTTP请求$this->bootstrap();【7、8】// 进入管道模式,经过中间件,然后处理用户的请求【9、10】return (new Pipeline($this->app))//创建管道->send($request) //发送请求->through($this->app->shouldSkipMiddleware() ? [] : $this->middleware) //通过中间件->then($this->dispatchToRouter()); //分发到路由
}
7、在bootstrap方法中,运行给定的引导类数组$bootstrappers,加载配置文件、环境变量、服务提供者、门面、异常处理、引导提供者,非常重要的一步
位置在vendor/laravel/framework/src/Illuminate/Foundation/Http/Kernel.php
/*** Bootstrap the application for HTTP requests.** @return void*/
public function bootstrap()
{if (! $this->app->hasBeenBootstrapped()) {$this->app->bootstrapWith($this->bootstrappers());}
}/*** 运行给定的引导类数组** @param string[] $bootstrappers* @return void*/
public function bootstrapWith(array $bootstrappers)
{$this->hasBeenBootstrapped = true;foreach ($bootstrappers as $bootstrapper) {$this['events']->dispatch('bootstrapping: '.$bootstrapper, [$this]);$this->make($bootstrapper)->bootstrap($this);$this['events']->dispatch('bootstrapped: '.$bootstrapper, [$this]);}
}/*** Get the bootstrap classes for the application.** @return array*/
protected function bootstrappers()
{return $this->bootstrappers;
}/*** 应用程序的引导类** @var array*/
protected $bootstrappers = [// 加载环境变量\\Illuminate\\Foundation\\Bootstrap\\LoadEnvironmentVariables::class,// 加载config配置文件【重点】\\Illuminate\\Foundation\\Bootstrap\\LoadConfiguration::class,// 加载异常处理\\Illuminate\\Foundation\\Bootstrap\\HandleExceptions::class,// 加载门面注册\\Illuminate\\Foundation\\Bootstrap\\RegisterFacades::class,// 加载在config/app.php中的providers数组里所定义的服务【8 重点】\\Illuminate\\Foundation\\Bootstrap\\RegisterProviders::class,// 记载引导提供者\\Illuminate\\Foundation\\Bootstrap\\BootProviders::class,
];
8、加载config/app.php中的providers数组里所定义的服务
Illuminate\\Auth\\AuthServiceProvider::class,
Illuminate\\Broadcasting\\BroadcastServiceProvider::class,
Illuminate\\Bus\\BusServiceProvider::class,
Illuminate\\Cache\\CacheServiceProvider::class,
Illuminate\\Foundation\\Providers\\ConsoleSupportServiceProvider::class,
Illuminate\\Cookie\\CookieServiceProvider::class,
Illuminate\\Database\\DatabaseServiceProvider::class,
Illuminate\\Encryption\\EncryptionServiceProvider::class,
Illuminate\\Filesystem\\FilesystemServiceProvider::class,
Illuminate\\Foundation\\Providers\\FoundationServiceProvider::class,
Illuminate\\Hashing\\HashServiceProvider::class,
Illuminate\\Mail\\MailServiceProvider::class,
Illuminate\\Notifications\\NotificationServiceProvider::class,
Illuminate\\Pagination\\PaginationServiceProvider::class,
Illuminate\\Pipeline\\PipelineServiceProvider::class,
Illuminate\\Queue\\QueueServiceProvider::class,
Illuminate\\Redis\\RedisServiceProvider::class,
Illuminate\\Auth\\Passwords\\PasswordResetServiceProvider::class,
Illuminate\\Session\\SessionServiceProvider::class,
Illuminate\\Translation\\TranslationServiceProvider::class,
Illuminate\\Validation\\ValidationServiceProvider::class,
Illuminate\\View\\ViewServiceProvider::class,
App\\Providers\\AppServiceProvider::class,
App\\Providers\\AuthServiceProvider::class,
App\\Providers\\EventServiceProvider::class,
App\\Providers\\RouteServiceProvider::class,
/*** 自己添加的服务提供者*/
\\App\\Providers\\HelperServiceProvider::class
可以看到,关于常用的 Redis、session、queue、auth、database、Route 等服务都是在这里进行加载的
9、使用管道模式处理用户请求,先经过中间件进行处理
return (new Pipeline($this->app))->send($request)// 如果没有为程序禁用中间件,则加载中间件(位置在app/Http/Kernel.php的$middleware属性)->through($this->app->shouldSkipMiddleware() ? [] : $this->middleware)->then($this->dispatchToRouter());
}
app/Http/Kernel.php
/*** 应用程序的全局HTTP中间件** These middleware are run during every request to your application.** @var array*/
protected $middleware = [\\App\\Http\\Middleware\\TrustHosts::class,\\App\\Http\\Middleware\\TrustProxies::class,\\Fruitcake\\Cors\\HandleCors::class,\\App\\Http\\Middleware\\CheckForMaintenanceMode::class,\\Illuminate\\Foundation\\Http\\Middleware\\ValidatePostSize::class,\\App\\Http\\Middleware\\TrimStrings::class,\\Illuminate\\Foundation\\Http\\Middleware\\ConvertEmptyStringsToNull::class
];
10、经过中间件处理后,再进行请求分发(包括查找匹配路由)
/*** 10.1 通过中间件/路由器发送给定的请求** @param \\Illuminate\\Http\\Request $request* @return \\Illuminate\\Http\\Response*/protected function sendRequestThroughRouter($request)
{...return (new Pipeline($this->app))...// 进行请求分发->then($this->dispatchToRouter());
}/*** 10.2 获取路由调度程序回调** @return \\Closure*/
protected function dispatchToRouter()
{return function ($request) {$this->app->instance('request', $request);// 将请求发送到应用程序return $this->router->dispatch($request);};
}/*** 10.3 将请求发送到应用程序** @param \\Illuminate\\Http\\Request $request* @return \\Illuminate\\Http\\Response|\\Illuminate\\Http\\JsonResponse*/public function dispatch(Request $request)
{$this->currentRequest = $request;return $this->dispatchToRoute($request);
}/*** 10.4 将请求分派到路由并返回响应【重点在runRoute方法】** @param \\Illuminate\\Http\\Request $request* @return \\Illuminate\\Http\\Response|\\Illuminate\\Http\\JsonResponse*/
public function dispatchToRoute(Request $request)
{//查询路由并执行路由return $this->runRoute($request, $this->findRoute($request));
}/*** 10.5 查找与给定请求匹配的路由** @param \\Illuminate\\Http\\Request $request* @return \\Illuminate\\Routing\\Route*/
protected function findRoute($request)
{// 匹配路由 $this->current = $route = $this->routes->match($request);$this->container->instance(Route::class, $route);return $route;
}/*** 10.6 查找与给定请求匹配的第一条路由** @param \\Illuminate\\Http\\Request $request* @return \\Illuminate\\Routing\\Route** @throws \\Symfony\\Component\\HttpKernel\\Exception\\NotFoundHttpException*/
public function match(Request $request)
{// 获取用户的请求类型(get、post、delete、put),然后根据请求类型选择对应的路由$routes = $this->get($request->getMethod());// 匹配路由$route = $this->matchAgainstRoutes($routes, $request);if (! is_null($route)) {return $route->bind($request);}$others = $this->checkForAlternateVerbs($request);if (count($others) > 0) {return $this->getRouteForMethods($request, $others);}throw new NotFoundHttpException;
}
到现在,已经找到与请求相匹配的路由了,之后将运行了,也就是10.4 中的runRoute 方法
/*** 10.4 将请求分派到路由并返回响应** @param \\Illuminate\\Http\\Request $request* @return \\Illuminate\\Http\\Response|\\Illuminate\\Http\\JsonResponse*/
public function dispatchToRoute(Request $request)
{return $this->runRoute($request, $this->findRoute($request));
}/*** 10.7 返回给定路线的响应** @param \\Illuminate\\Http\\Request $request* @param \\Illuminate\\Routing\\Route $route* @return \\Illuminate\\Http\\Response|\\Illuminate\\Http\\JsonResponse*/
protected function runRoute(Request $request, Route $route)
{$request->setRouteResolver(function () use ($route) {return $route;});$this->events->dispatch(new Events\\RouteMatched($route, $request));return $this->prepareResponse($request,$this->runRouteWithinStack($route, $request));
}/*** Run the given route within a Stack "onion" instance.* 10.8 在栈中运行路由** @param \\Illuminate\\Routing\\Route $route* @param \\Illuminate\\Http\\Request $request* @return mixed*/
protected function runRouteWithinStack(Route $route, Request $request)
{$shouldSkipMiddleware = $this->container->bound('middleware.disable') &&$this->container->make('middleware.disable') === true;$middleware = $shouldSkipMiddleware ? [] : $this->gatherRouteMiddleware($route);return (new Pipeline($this->container))->send($request)->through($middleware)->then(function ($request) use ($route) {return $this->prepareResponse($request, $route->run());});
}
11、运行路由并返回响应[重点]
可以看到,10.7 中有一个方法是prepareResponse,该方法是从给定值创建响应实例,而 runRouteWithinStack 方法则是在栈中运行路由,也就是说,http的请求和响应都将在这里完成
prepareResponse
调用toResponse,最后执行prepare
public function prepare(Request $request)
{$headers = $this->headers;if ($this->isInformational() || $this->isEmpty()) {$this->setContent(null);$headers->remove('Content-Type');$headers->remove('Content-Length');// prevent PHP from sending the Content-Type header based on default_mimetypeini_set('default_mimetype', '');} else {// Content-type based on the Requestif (!$headers->has('Content-Type')) {$format = $request->getRequestFormat(null);if (null !== $format && $mimeType = $request->getMimeType($format)) {$headers->set('Content-Type', $mimeType);}}// Fix Content-Type$charset = $this->charset ?: 'UTF-8';if (!$headers->has('Content-Type')) {$headers->set('Content-Type', 'text/html; charset='.$charset);} elseif (0 === stripos($headers->get('Content-Type'), 'text/') && false === stripos($headers->get('Content-Type'), 'charset')) {// add the charset$headers->set('Content-Type', $headers->get('Content-Type').'; charset='.$charset);}// Fix Content-Lengthif ($headers->has('Transfer-Encoding')) {$headers->remove('Content-Length');}if ($request->isMethod('HEAD')) {// cf. RFC2616 14.13$length = $headers->get('Content-Length');$this->setContent(null);if ($length) {$headers->set('Content-Length', $length);}}}// Fix protocolif ('HTTP/1.0' != $request->server->get('SERVER_PROTOCOL')) {$this->setProtocolVersion('1.1');}// Check if we need to send extra expire info headersif ('1.0' == $this->getProtocolVersion() && str_contains($headers->get('Cache-Control', ''), 'no-cache')) {$headers->set('pragma', 'no-cache');$headers->set('expires', -1);}$this->ensureIEOverSSLCompatibility($request);if ($request->isSecure()) {foreach ($headers->getCookies() as $cookie) {$cookie->setSecureDefault(true);}}return $this;
}
12、返回response($response->send();
)
public function send()
{// 发送headers头 12.1$this->sendHeaders();// 发送返回内容 12.2$this->sendContent();if (\\function_exists('fastcgi_finish_request')) {fastcgi_finish_request();} elseif (!\\in_array(\\PHP_SAPI, ['cli', 'phpdbg'], true)) {static::closeOutputBuffers(0, true);}return $this;
}
12.1、发送HTTP报头
public function sendHeaders()
{// headers have already been sent by the developerif (headers_sent()) {return $this;}// headersforeach ($this->headers->allPreserveCaseWithoutCookies() as $name => $values) {$replace = 0 === strcasecmp($name, 'Content-Type');foreach ($values as $value) {header($name.': '.$value, $replace, $this->statusCode);}}// cookiesforeach ($this->headers->getCookies() as $cookie) {header('Set-Cookie: '.$cookie, false, $this->statusCode);}// statusheader(sprintf('HTTP/%s %s %s', $this->version, $this->statusCode, $this->statusText), true, $this->statusCode);return $this;
}
12.2、为当前响应发送内容
public function sendContent()
{// 输出当前内容echo $this->content;return $this;
}
13、程序终止($kernel->terminate($request, $response);
)
public function terminate($request, $response)
{// 13.1 执行程序终止前的中间件回调$this->terminateMiddleware($request, $response);$this->app->terminate();
}
13.1、在任何可终止的中间件上调用terminate方法
protected function terminateMiddleware($request, $response)
{// 获取要执行的中间件,并合并路由中间件$middlewares = $this->app->shouldSkipMiddleware() ? [] : array_merge($this->gatherRouteMiddleware($request),$this->middleware);foreach ($middlewares as $middleware) {if (! is_string($middleware)) {continue;}[$name] = $this->parseMiddleware($middleware);$instance = $this->app->make($name);// 判断是否存在terminate方法,存在则调用if (method_exists($instance, 'terminate')) {$instance->terminate($request, $response);}}
}
laravel源码分析相关推荐
- Laravel源码分析之Session
由于HTTP最初是一个匿名.无状态的请求/响应协议,服务器处理来自客户端的请求然后向客户端回送一条响应.现代Web应用程序为了给用户提供个性化的服务往往需要在请求中识别出用户或者在用户的多条请求之间共 ...
- Laravel源码分析之模型关联
上篇文章我们主要讲了Eloquent Model关于基础的CRUD方法的实现,Eloquent Model中除了基础的CRUD外还有一个很重要的部分叫模型关联,它通过面向对象的方式优雅地把数据表之间的 ...
- Laravel源码学习文章汇总
过去一年时间写了20多篇文章来探讨了我认为的Larave框架最核心部分的设计思路.代码实现.通过更新文章自己在软件设计.文字表达方面都有所提高,在刚开始决定写Laravel源码分析地文章的时候我地期望 ...
- laravel $request 多维数组取值_Laravel 运行原理分析与源码分析,底层看这篇足矣
精选文章内容 一.运行原理概述 laravel的入口文件 index.php 1.引入自动加载 autoload.php 2.创建应用实例,并同时完成了: 基本绑定($this.容器类Containe ...
- Laravel核心解读--Cookie源码分析
Laravel Cookie源码分析 使用Cookie的方法 为了安全起见,Laravel 框架创建的所有 Cookie 都经过加密并使用一个认证码进行签名,这意味着如果客户端修改了它们则需要对其进行 ...
- 【Golang源码分析】Go Web常用程序包gorilla/mux的使用与源码简析
目录[阅读时间:约10分钟] 一.概述 二.对比: gorilla/mux与net/http DefaultServeMux 三.简单使用 四.源码简析 1.NewRouter函数 2.HandleF ...
- ThinkPHP5.1.x 框架源码分析之框架的灵魂
一.类的自动加载初始 框架的灵魂,类的自动加载 为什么说是框架灵魂呢,一般框架都会有类的自动加载,当引入文件很多的时候,就会需要用到.这一个也是很多人想去阅读源码时卡住的点 源码阅读 打开到入口文件 ...
- Laravel源码剖析之请求的处理上(四)
上篇讲了make方法-->Laravel源码剖析之make详解(三)_Attitude_do_it的博客-CSDN博客, 根据make方法的分析可以得出: $kernel = $app-> ...
- SpringBoot-web开发(四): SpringMVC的拓展、接管(源码分析)
[SpringBoot-web系列]前文: SpringBoot-web开发(一): 静态资源的导入(源码分析) SpringBoot-web开发(二): 页面和图标定制(源码分析) SpringBo ...
最新文章
- 08_传智播客iOS视频教程_点语法
- bat 域 本机管理员密码_域渗透——Local Administrator Password Solution
- GDataXML的一些简单示例。
- 让人惊叹的Johnson-Lindenstrauss引理:理论篇
- VTK:几何对象之Frustum
- jq 组装数组_Jquery 数组操作
- 达观数据:Tornado原理浅析及应用场景探讨
- LeetCode中等题之整数转罗马数字
- 16种常用的数据分析方法-相关分析
- 听某个老师的ElasticSearch记的笔记了
- 【转】我是一个INFP者
- 声音均衡器怎么调好听_酷狗均衡器怎么调好听 - 卡饭网
- 如何准备数学建模竞赛
- 蓝桥杯 动态数码管中的延时处理
- 网站服务器对clu,web服务器解释html-include
- The Great Gatsby翻译摘录
- VC2013下,使用curl
- Sony xperia xz1compact - 重刷固件ROM和解锁ROOT教程
- 基于SSH的实验室预约管理系统【数据库设计、源码、开题报告】
- [zz]各大IT公司待遇